Creating an instance from String in Java

前端 未结 2 1044
遥遥无期
遥遥无期 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 05:50
    Class c= Class.forName(className);
    return c.newInstance();//assuming you aren't worried about constructor .
    
    • javadoc

    For invoking constructor with argument

     public static Object createObject(Constructor constructor,
          Object[] arguments) {
    
        System.out.println("Constructor: " + constructor.toString());
        Object object = null;
    
        try {
          object = constructor.newInstance(arguments);
          System.out.println("Object: " + object.toString());
          return object;
        } catch (InstantiationException e) {
          //handle it
        } catch (IllegalAccessException e) {
          //handle it
        } catch (IllegalArgumentException e) {
          //handle it
        } catch (InvocationTargetException e) {
          //handle it
        }
        return object;
      }
    }
    

    have a look

    0 讨论(0)
  • 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;
       }
    }
    
    0 讨论(0)
提交回复
热议问题