简体   繁体   English

我可以在Java中为“类”而不是“对象”定义“接口”吗?

[英]Could I define a 'Interface' for 'Class' instead of 'Object' in java?

We know 'interface' in java provide a common way to access objects who implementing it, but i wonder if there's a way like interface which not just for accessing the object's method, but also for accessing the class's method(static method). 我们知道Java中的“接口”提供了一种访问访问实现它的对象的通用方法,但是我想知道是否存在像接口这样的方法,它不仅可以访问对象的方法,而且还可以访问类的方法(静态方法)。 I want to use it to invoke an array of different classes's static factory method. 我想用它来调用不同类的静态工厂方法的数组。 Does java provide something like it? java是否提供类似的东西?

No. 没有。

But you can implement the pattern you describe easily with an ordinary object interface, then a set of classes that just wrap the static methods you wish to call through to. 但是您可以使用一个普通的对象接口轻松实现您描述的模式,然后使用一组只包装您希望调用的静态方法的类来实现。

If your intentions is to call static method of an implementing class using Interface reference, the answer is No. static members belong to class only, so you will always need a Class type reference (actually it should be the class name) to access them. 如果您打算使用接口引用调用实现类的静态方法,则答案是“否”。静态成员仅属于类,因此您将始终需要Class类型引用(实际上应该是类名)来访问它们。

With interfaces you can only point to what you have declared in it. 使用接口,您只能指向您在其中声明的内容。

No, there's no kind of "interface for static methods" in Java. 不,Java中没有“静态方法的接口”。

(Aside from anything else, how would you expect to specify the class in question? Even generics wouldn't help here due to type erasure.) (除了别的什么,您希望如何指定有问题的类?由于类型擦除,即使泛型在这里也无济于事。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM