如何从使用类加载器创建的类调用方法


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()

最方便的方法是两个类加载器都可以使用方法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);

最新更新