在Java中从String创建实例
如果我有2个类,“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(); }
谢谢!
乔尔
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; } }
看看
你可以看一下反思 :
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; } }