我是 Java 新手,但我了解基础知识。我知道接口(interface)是抽象类,它们用于模拟多重继承(有点 - 我知道在 Java 中这是不允许的)。我有这个代码;你能给我解释一下吗?
这是迭代类列表的方法的一部分:
Constructor[] c = aClass.getConstructors();
for (Constructor constructor : c) {
if (constructor.getParameterTypes().length == 0) {
AInterface action = (AInterface) constructor.newInstance();
try {
action.run(request, response);
}
}
}
下面是上面代码使用的接口(interface)定义:
public interface AInterface
{
void run(HttpServletRequest request, HttpServletResponse response);
}
最佳答案
它使用 reflection使用其零参数构造函数(如果有的话)创建其 java.lang.Class
对象存储在 aClass
变量中的类的实例,然后调用其方法之一(假定实现 AInterface
)。
该代码看起来像是来自某个 Web 框架。你为什么看它?反射是 Java 中比较高级的东西之一,通常不是初学者需要处理的东西。
For what is calling the method run, if the method run hasn't a body? For what is good?
创建的类 (aClass
) 是一个具体类,而不是接口(interface),它将实现该接口(interface)并包含 run
方法的主体。您需要了解有关界面的更多信息(Google 是您的 friend )。
关于java - 使用类和接口(interface)的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1512127/