简体   繁体   中英

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

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

The most convinient way of doing this having an interface with method disp available to both classloaders. Secondclass can implement that interface and you can cast any instance created by the class to the interface. This can be done quite convinient with 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM