KARTHIK NN
KARTHIK NN

Reputation: 11

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

Upvotes: 0

Views: 2190

Answers (1)

k5_
k5_

Reputation: 5558

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

Upvotes: 1

Related Questions