在 Java 中,有一个 Class
无需实例化即可用于表示其他类的类。例如:
Class[] foo = { ArrayList.class, String.class, Character.class, Integer.class, MyCustomClass.class };
ArrayList bar = foo[0].newInstance();
将是有效代码。例如,我还可以遍历 Object
的数组,并对所有对象执行 instanceof
检查,以找到 foo
中的相应类阵列,具有潜在的应用。
Java 中是否存在interfaces 这样的类? ?是否有一些类(class)我可以做类似这样的事情:
Interface[] foo = {Comparable, List<String>, MyCustomInterface}
从 Java 8 开始,接口(interface)现在可以有静态方法,这种行为可能很有用,如果不好的话。存在吗?
最佳答案
接口(interface)只是一个类 Class.isInterface()
返回真。所以:
Class<?>[] foo = {Comparable.class, List.class, MyCustomInterface.class};
请注意,没有通用类实例,例如List<String>
: 它只是原始的 List.class
.
关于Java "Interface"类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37424252/