I assume you want to create a new instance of that class. This would not be possible using generics (you can't call new T()
) and would also be quite limited using reflection.
The reflection approach could be:
//class is a reserved word, so use clazz
public <T> T getObject(Class<T> clazz) {
try {
return clazz.newInstance();
}
catch( /*a multitude of exceptions that can be thrown by clazz.newInstance()*/ ) {
//handle exception
}
}
Note that this only works if the class has a no-argument constructor.
However, the question would by why you need that instead of just calling
new WhatEverClassYouHave()
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…