开发者

Dynamic class loading with Java

开发者 https://www.devze.com 2023-03-31 02:03 出处:网络
I want to dynamically load a concrete class which implements an interface. Input: concrete class name.

I want to dynamically load a concrete class which implements an interface. Input: concrete class name.

开发者_Go百科

I need to call a method in this concrete class, that is, I'll need to set:

MyInterface myclass = new concreteClassName();
myclass.function();

How can I achieve this?


have a look at Class.forName(String)

    String str = "Test$B"; //your full class name here instead of Test$B
    A clazz = null; //change A to be your interface
    try { 
    clazz = (A)Class.forName(str).newInstance(); //change A to be your interface

    } catch (Exception e) { 
        //TODO: handle exceptions
        e.printStackTrace();
    }
    if (clazz != null)  {
        clazz.foo();
    }


Have you checked out

try {
     // Load class
     Class<?> cls = Class.forName("my.package.ConcreteClass");

     // Instantiate object from class using default constructor
     my.package.ConcreteClass obj = (my.package.ConcreteClass) cls.newInstance(); 

     // Execute method on it
     obj.myMethod(); 
} catch (Exception e) {
    throw new RuntimeException("Could not instantiate class", e);
}

and the respective javadoc entries for Class#forName and Class#newInstance?


You should implement your own ClassLoader.

0

精彩评论

暂无评论...
验证码 换一张
取 消