[英]How to call a method from class created using classloader
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();
}
}
}
Second program is 第二个程序是
public class secondclass
{
public void disp()
{
System.out.println("Clss B is Called")
}
}
when i execute this program i get output as 当我执行此程序时,我得到的输出为
Class A called
x has been initializedsecondclass
but if try to call x.disp()
or 但是如果尝试调用x.disp()
或
Object y=x.newInstance();
y.disp();
then i get the error as object not found. 然后我得到错误,因为找不到对象。 how to get the object of x to call disp() 如何获取x的对象以调用disp()
The most convinient way of doing this having an interface with method disp
available to both classloaders. 最方便的方法是使用两个类加载器都可以使用方法disp
的接口。 Secondclass can implement that interface and you can cast any instance created by the class to the interface. Secondclass可以实现该接口,并且您可以将由该类创建的任何实例强制转换为该接口。 This can be done quite convinient with spi https://docs.oracle.com/javase/tutorial/ext/basics/spi.html 使用spi https://docs.oracle.com/javase/tutorial/ext/basics/spi.html可以非常方便地完成此操作
If you can't use an interface you need reflection. 如果您不能使用界面,则需要进行反思。
Class<?> type = classLoader.loadClass("secondclass");
Object instance = type.getConstructor().newInstance();
type.getMethod("disp").invoke(instance);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.