简体   繁体   English

使用Java加载动态类

[英]Dynamic class loading with Java

I want to dynamically load a concrete class which implements an interface. 我想动态加载实现接口的具体类。 Input: concrete class name. 输入:具体的类名。

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) 看看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 ? 以及Class#forNameClass#newInstance的相应javadoc条目?

您应该实现自己的ClassLoader

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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