Creating an instance from String in Java

前端 未结 2 1104
遥遥无期
遥遥无期 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

提交回复
热议问题