Dynamically loading a class in Java

后端 未结 3 2030
时光取名叫无心
时光取名叫无心 2020-12-06 04:37

I looked up the syntax and searched the api but am still confused about the process. I also searched Stackoverflow. What is the proper way to load a class and create an obj

3条回答
  •  借酒劲吻你
    2020-12-06 05:02

    ClassLoader.loadClass will load a class. You get a classloader by myClass.getClassLoader() and you should fall back to ClassLoader.getSystemClassLoader() if that is null.

    Once you've got a class instance, you can get its constructors via getDeclaredConstructor(...). So if you have a public class MyClass with a constructor like public MyClass(String) { ... } then

    Class clazz = MyClass.class;
    Constructor ctor = clazz.getDeclaredConstructor(String.class);
    MyClass instance = ctor.newInstance("foo");
    

    The above ignores a bunch of possible exceptions.

提交回复
热议问题