使用类和接口的代码

时间:2009-10-02 22:36:45

标签: java interface

我是Java的新手,但我了解基础知识。我知道接口是抽象类,它们用于模拟多重继承(有点 - 我知道在Java中这是不允许的)。我有这个代码;你能解释一下吗?

以下是迭代类列表的方法的一部分:

Constructor[] c = aClass.getConstructors();
for (Constructor constructor : c) {
  if (constructor.getParameterTypes().length == 0) {
    AInterface action = (AInterface) constructor.newInstance();
    try {
      action.run(request, response);
    }
  }
}

以下是上述代码使用的接口定义:

public interface AInterface 
{
  void run(HttpServletRequest request, HttpServletResponse response);
}

3 个答案:

答案 0 :(得分:2)

它正在为类AClass寻找一个0参数构造函数。不会超过一个。 :)

然后使用该构造函数创建该类的实例。

然后用两个对象调用该类的“run”方法。

希望这有帮助。

答案 1 :(得分:2)

使用reflection创建一个类的实例,其java.lang.Class对象存储在aClass变量中,使用它的零参数构造函数(如果有的话),然后调用其中一个方法(假设它实现AInterface)。

该代码看起来像是来自某个Web框架。你为什么看着它?反思是关于Java的更高级的事情之一,而不是初学者通常需要处理的事情。

  

对于调用方法运行的内容,如果方法运行没有正文?什么是好的?

创建的类(aClass)是一个具体的类,而不是一个接口,它将实现接口并包含run方法的主体。您需要了解有关界面的更多信息(Google是您的朋友)。

答案 2 :(得分:2)

Constructor[] c = aClass.getConstructors();  // Retrieve all the constructors 
                                             // of the class 'aClass' 
for (Constructor constructor : c) { // Iterate all constructors
    // Until the only default constructor is found.
    if (constructor.getParameterTypes().length == 0) { 
    // Create a new instance of 'aClass' using the default constructor
    // Hope that 'aClass' implements 'AInterface' otherwise ClassCastException ...
    AInterface action = (AInterface) constructor.newInstance();
    try {
      // action has been cast to AInterface - so it can be used to call the run method
      // defined on the AInterface interface. 
      action.run(request, response);
    } // Oops - missing catch and/or finally. That won't compile
  }
}
// Missing a bit of error handling here for the countless reflection exception
// Unless the method is declared as 'throws Exception' or similar

使用示例:

你有一个名为'TheClass'的课程

public class TheClass implements AInterface {
    public void run(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("Hello from TheClass.run(...)");
        // Implement the method ...
    }
}

应用程序中的某个位置,使用Reflection或读取配置文件。 应用程序发现它应该执行'TheClass'。 你没有关于'TheClass'的任何指示,它应该实现AInterface并且它有一个默认的构造函数。

您可以使用

创建Class对象
Class aClass = Class.forName("TheClass");

并在之前的代码段中使用'aClass'(在添加错误处理代码之后)。你应该在控制台中看到

Hello from TheClass.run(...)
相关问题