简体   繁体   English

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

[英]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.

相关问题 如何使用classLoader从加载的类中调用方法? - How to call a method from loaded class using classLoader? 如何从另一个类方法调用已创建对象的方法? - How to call a method of an already created object from another class method? Java:如何从类中创建的对象调用类方法? - Java: How to call a class method from an object created in the class? 如何从通过类加载器加载的 class 调用构造函数 - How to call constructor from class loaded via classloader 如何声明由类加载器加载的 class 创建的 object - How to declare an object created by a class loaded by classloader 如何在创建另一个 class 的 object 后调用方法 - How to call a method after a object from another class is created 使用ClassLoader.defineClassCond从通过ASM创建的类的字节中获取Class对象,NoClassDefFoundException? - Using ClassLoader.defineClassCond to get a Class object from bytes of a class created through ASM, NoClassDefFoundException? 我如何使用ClassLoader从另一个项目中加载类 - How can i load a class from another project using ClassLoader 如何从类型变量获取ClassLoader(使用泛型对类进行分区) - How to get ClassLoader from type variable (for parceling a class using generics) 如何在java中使用类加载器获取数组类? - how to get a array class using classloader in java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM