在Java中调用参数化类的静态方法
我有一个扩展同一个超类的类列表,其中有一个名为 foo 的静态字段:
List<Class<? extends SuperClass>> list;
如何访问该列表的元素上的 foo ?
I have a list of classes that extend the same superclass, which has a static field called foo:
List<Class<? extends SuperClass>> list;
how can I access foo on an element of that list?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么
不应该工作?由于它是静态的,因此您的
List
完全无关。还有子类,因为该字段在Superclass
中只存在一次。Why should
not work? Since it is static, your
List
is completely irrelevant. And also the child classes, since the field exists exactly once inSuperclass
.您可以通过类名访问超类上的静态字段 foo:
静态字段在所有实例和所有子类中都具有一个值。
You can access a static field foo on a superclass through the class name:
A static field has one value across all instances and all subclasses.
类名及其静态成员:
The class name and his static member:
我认为这里的问题是你试图在类上调用静态方法,而不是在超类的子类上调用静态方法。
假设您有一个类 Foo,它有一个返回字符串的静态方法 bar。您可以这样做:
但不能这样做:
您的示例中的内容更像是这样:
解决方案: 此时您应该能够使用反射来调用该方法:
I think the problem here is that you're trying to call a static method on a Class, not on a class that's a child of SuperClass.
Say you have a Class Foo that has a static method bar that returns a String. You can do this:
but you can't do this:
What you have in your example would be more like this:
Solution: You should be able to use reflection at this point to call the method:
您可以使 foo 受到保护,这样您就可以在子类中访问它。
You could make foo protected, that way you can access it in a subclass.