Creating an instance from String in Java

前端 未结 2 1128
遥遥无期
遥遥无期 2020-12-05 05:12

If I have 2 classes, \"A\" and \"B\", how can I create a generic factory so I will only need to pass the class name as a string to receive an instance?

Example:

2条回答
  •  无人及你
    2020-12-05 06:06

    You may take a look at Reflection:

    import java.awt.Rectangle;
    
    public class SampleNoArg {
    
       public static void main(String[] args) {
          Rectangle r = (Rectangle) createObject("java.awt.Rectangle");
          System.out.println(r.toString());
       }
    
       static Object createObject(String className) {
          Object object = null;
          try {
              Class classDefinition = Class.forName(className);
              object = classDefinition.newInstance();
          } catch (InstantiationException e) {
              System.out.println(e);
          } catch (IllegalAccessException e) {
              System.out.println(e);
          } catch (ClassNotFoundException e) {
              System.out.println(e);
          }
          return object;
       }
    }
    

提交回复
热议问题