0
import java.lang.*;
public class firstclass
{
public static void main(String[] args)
{ ClassLoader classLoader = firstclass.class.getClassLoader();

    System.out.println("class A is called ...");
         try {
        Class x=classLoader.loadClass("secondclass");
         System.out.println("x has been initialized"+x);
         //Object y=x.newInstance();
         //y.disp();
      } catch (Exception e) {
         e.printStackTrace();

      } 

}
}

第二个程序是

public class secondclass
{
public void disp()
{
System.out.println("Clss B is Called")
}
}

当我执行这个程序时,我得到的输出为

Class A called
x has been initializedsecondclass

但如果尝试打电话x.disp()

Object y=x.newInstance();
y.disp();

然后我得到错误,因为找不到对象。如何让 x 的对象调用 disp()

4

1 回答 1

1

最方便的方法是disp使用两个类加载器都可以使用的方法接口。Secondclass 可以实现该接口,您可以将该类创建的任何实例强制转换为该接口。这可以通过 spi https://docs.oracle.com/javase/tutorial/ext/basics/spi.html非常方便地完成

如果您不能使用接口,则需要反射。

    Class<?> type = classLoader.loadClass("secondclass");
    Object instance = type.getConstructor().newInstance();
    type.getMethod("disp").invoke(instance);
于 2016-07-16T08:14:23.837 回答