2014-01-17 45 views
2

我有一個類叫做Creator,它包含兩個實例字段。這些字段屬於父類A.在創建者的構造函數中,我想傳遞類A的子類,然後從傳入的類型創建兩個對象並將引用分配給這兩個字段。我該如何做這樣的事情?我不知道如何做出這個概括。如何通過傳遞對象類型來創建多個對象?

編輯:類創建者只有接受A或A本身的孩子的類型。所以不是其他任何一般類型。 AND A沒有一個無參數的構造

所以這樣的,這裏GeneralClassifier是A,沒有一個無參數的構造函數:

public class TwoLevelClassifier <T> { 

    private GeneralClassifier firstCl, secondCl; 

    //The passed type shall *only* be a GeneralClassifier or a child of it 
    public TwoLevelClassifier(GeneralClassifier cl) { 
     firstCl = //create a new classifier that is of the type passed to the constructor 
     secondCl = //create a new classifier that is of the type passed to the constructor 
    } 

} 

我不知道,但也許這功能在java中稱爲泛型?

+1

你應該使用反射。看到這個:http://stackoverflow.com/questions/10470263/create-new-object-using-reflection – Massimo

+1

爲什麼不使用泛型? 'public class Creator {' – crush

+0

是否需要將兒童類型的實例作爲ctor的參數傳遞?你沒有做任何事情,所以我不假設 – crush

回答

7

爲此,您可以使用反射:

public class Creator<A> { 
    A a, b; 

    public Creator(Class<A> childrenType) throws IllegalAccessException, InstantiationException { 
     a = childrenType.newInstance(); 
     b = childrenType.newInstance(); 
    } 
} 

注:這是假設您使用的類有一個無參數的構造函數。

編輯你基本上編輯了你的原始問題。

對於要求該類型A應該只是一個GeneralClassifier或者一個子類,添加一個約束的類型參數:

public class Creator<A extends GeneralClassifier> { 

對於該類A沒有無糖的要求參數構造函數:然後,您必須查找要使用的構造函數,並使用適當的參數調用它。你必須事先知道你需要調用哪個構造函數。假設你想調用一個需要String的構造函數。然後,它會是這樣的:

Constructor<A> constr = childrenType.getConstructor(String.class); 
a = constr.newInstance("Hello"); 
b = constr.newInstance("Bye"); 

java.lang.Class類的API文檔和包java.lang.reflect

+1

答案沒問題,但我應該指出,使用反射應該總是最後的手段。 –

+0

是泛型和反射相同的東西? –

+0

不,不,不。他們是非常非常不同 – Zavior

3

你可以做反射和泛型類似的東西,像這樣

// <TYPE> is the generic type. 
public class Creator<TYPE> { 
    TYPE a = null, b = null; 

    public Creator(Class<TYPE> childrenType) { 
     try { 
      // newInstance is reflection. 
      a = childrenType.newInstance(); 
      b = childrenType.newInstance(); 
     } catch (InstantiationException e) { 
      e.printStackTrace(); 
     } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
     } 
    } 
} 

或者,你可以通過在TYPE的情況下,與此構造(例如)避免反射 -

public Creator(TYPE a, TYPE b) { 
    this.a = a; 
    this.b = b; 
} 
+0

你能解釋'newInstance()'如何使用反射嗎? – Keerthivasan

+0

[爲什麼Class.newInstance「邪惡」?](http://stackoverflow.com/questions/195321/why-is-class-newinstance-vil) – crush

+0

@Octopus因爲它需要運行時檢查,讀[javadoc ](http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#newInstance%28%29)特別注意例外情況。 –

相關問題