java - 使用类和接口(interface)的代码

标签 java interface

我是 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/

相关文章:

c# - 显式接口(interface)实现限制

java - 当所有其他实例都正确时,为什么我会返回错误的 boolean 值?

android - Activity和Fragment之间如何回调?

java - CAS:用户以其他用户身份登录

java - 如何在 Java 中更新 MongoDb 数据库?

java - 测试方法是否以同步方式运行

java - 使用 DOM 解析器 Java 解析具有嵌套重复元素名称的 xml 文档。

c# - IsAssignableFrom 或 AS?

mongodb - 将 mgo 与转换为 map[string]interface{} 的嵌套文档一起使用。如何遍历 map ?

Java - JTable - getSelectedRow() 中的数据错误