2012-01-28 60 views
0

我试图做一个函数,使用扩展Foo的许多类中的一个,并在其类中返回该对象的新实例,而不是新实例Foo基于参数的类的新实例

我确定这是一个常见问题。那里有没有好的例子?

我从来没有使用过一个类作为输入参数,只有一个类的成员。根据我搜索的内容,这应该可以做到吗?

回答

1

你是通过一个Class对象作为参数,还是在Foo的子类的实例?

无论哪种情况,解决方案都几乎相同,您可以在Class对象上使用newInstance方法。

/** 
* Return a new subclass of the Foo class. 
*/ 
public Foo fooFactory(Class<? extends Foo> c) 
{ 
    Foo instance = null; 
    try { 
     instance = c.newInstance(); 
    } 
    catch (InstantiationException e) { 
     // ... 
    } 
    catch (IllegalAccessException e) { 
     // ... 
    } 
    return instance; // which might be null if exception occurred, 
        // or you might want to throw your own exception 
} 

如果您需要构造ARGS可以使用getConstructor类的方法,并从那里的构造newInstance(...)方法。

+0

谢谢队友。似乎现在正在工作。对于其他阅读,在此之后,我得到了一个例外,并与此线程解决:http://stackoverflow.com/questions/2120699/newinstance-failed-no-init – SpiRail 2012-01-28 15:02:27

0

您可以在这里使用Java的反射。

如果你想只是它的类名获得Class,您使用Class.forName

Class type = Class.forName('package.SomeClass'); 

您可以检查这个类是Foo或它的子类:

boolean isFoo = type.isAssignableFrom(Foo.class); 

你可以那么很容易创建一个新的实例(假设构造函数不带参数):

Object instance = type.newInstance(); 
1

你的函数可以是这样的

public class NewInstanceTest { 
    public static Object getNewInstance(Foo fooObject){ 
     java.lang.Class fooObjectClass = fooObject.getClass(); 
     try { 
      return fooObjectClass.newInstance(); 
     } catch (InstantiationException e) { 
      e.printStackTrace(); 
      return null; 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
      return null; 
     } 
} 
public static void main(java.lang.String[] args){ 
     // This prints Foo 
     java.lang.System.out.println(getNewInstance(new Foo()).getClass().getName()); 
     // This prints Foo1 
     java.lang.System.out.println(getNewInstance(new Foo1()).getClass().getName()); 
} 
} 
class Foo{ 
} 
class Foo1 extends Foo{ 
} 

希望这有助于。