在java中从字符串创建示例

xn1cxnb4  于 2021-08-20  发布在  Java
关注(0)|答案(2)|浏览(237)

如果我有两个类,“a”和“b”,如何创建一个通用工厂,这样我只需要将类名作为字符串传递就可以接收示例?
例子:

public static void factory(String name) {
     // An example of an implmentation I would need, this obviously doesn't work
      return new name.CreateClass();
}

谢谢
乔尔

jk9hmnmh

jk9hmnmh1#

Class c= Class.forName(className);
return c.newInstance();//assuming you aren't worried about constructor .

javadoc
用于使用参数调用构造函数

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;
  }
}

看一看

hof1towb

hof1towb2#

您可以查看反射:

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;
   }
}

相关问题