所以我有以下的通用類:如何獲取泛型類的對象類型?
public class Member<T> {
private T id;
private T complexityLevel;
//constructor
public Member(T id, T complexityLevel) {
this.id = id;
this.complexityLevel = complexityLevel;
}
public T getId() {
return id;
}
public T getComplexity() {
return complexityLevel;
}
public void setComplexity(T complexityLevel) {
this.complexityLevel = complexityLevel;
}
public void setId(T id) {
this.id = id;
}
public static void main(String[] args) {
Member<String> mString = new Member<String>("id1", "High");
System.out.printf("id before setting id: %s%n", mString.getId());
mString.setId("id2");
System.out.printf("id after setting id: %s%n", mString.getId());
System.out.printf("complexity before setting it: %s%n", mString.getComplexity());
mString.setComplexity("Low");
System.out.printf("complexity after setting it: %s%n", mString.getComplexity());
// now for an integer
Member<Integer> mInteger = new Member<Integer>(1, 100);
System.out.printf("id before setting id: %d%n", mInteger.getId());
mInteger.setId(2);
System.out.printf("id after setting id: %d%n", mInteger.getId());
// for Double
Member<Double> mDouble = new Member<Double>(100.0);
...
我試圖獲得Member
類的對象基本類型(String
,Integer
,Double
等)。到目前爲止,我有這一點,但問題是它返回"Member"
:
System.out.println(mString.getClass().getName());
System.out.println(mInteger.getClass().getName());
System.out.println(mDouble.getClass().getName());
謝謝。我得到「java.lang.String」,「java.lang.Integer」和「java.lang.Double」。我可以用它來獲取子字符串。基本上我需要確定我正在執行的測試用例的參數類型。 – nabsATX
@neal_fazio - 你問如何得到「字符串」,「整數」等?你可以使用'getSimpleName()'而不是'getName()'。 –
完美。我想我需要熟悉一些更多的Java API。 – nabsATX