2011-01-22 79 views
15

如果我有2个类“A”和“B”,如何创建一个通用工厂,这样我只需要将类名作为字符串传递以接收实例?从Java中的字符串创建实例

例子:

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

谢谢!

乔尔

+4

您正在重返`void` – 2011-01-22 09:25:34

回答

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

对于参数调用构造函数

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

look

+0

我如何发送参数构造函数? – Joel 2011-01-22 09:36:59

4

你可以看看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; 
    } 
}