2009-10-02 42 views
0

我是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); 
} 
+1

您尚未明确指出您的问题,但我可以告诉您接口与抽象类不同。 – Mike 2009-10-02 22:39:40

+0

http://mindprod.com/jgloss/interfacevsabstract。html – Mike 2009-10-02 22:40:20

+0

看起来像一些疯狂的Command模式代表团。对于某个java新手来说,这是一个相当粗糙的问题。 – 2009-10-02 22:41:41

回答

2

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

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

什么是调用方法运行,如果方法运行没有正文?什么是好?

其中创建的类(aClass)是一个具体的类,而不是一个接口,它将实现接口并包含run方法的主体。你需要了解更多关于界面的知识(Google是你的朋友)。用法

2

它寻找一个0参数的类AClass的构造函数。不会有一个以上。 :)

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

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

希望这会有所帮助。

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 ... 
    } 
} 

某处在应用程序类,或者使用反射或读取配置文件。 应用程序发现它应该执行'TheClass'。 你没有任何关于'TheClass'的指示,它应该实现AInterface,它有一个默认的构造函数。

可以使用

Class aClass = Class.forName("TheClass"); 

创建类对象,并在您使用“ACLASS”前面的代码片段(添加代码ErrorHandling中后)。您应该在控制台中看到

 
Hello from TheClass.run(...)