Re: How to create an instance of type T?
Joshua Cranmer wrote:
prowyh wrote:
I want to write a generic method that return the specified object
constructed with type parameter T and the parameter of type String.
Wherefore?
class GClass<T>
{
public T getValue(String p) throws Exception
{
// create and instance of type T or a Class class of type T
// construct the object with p by reflection
// return the object
}
}
You'll need to modify the code here somewhat:
class GClass<T> {
private Class<T> clazz;
public GClass<T>(Class<T> clazz) {
this.clazz = clazz;
}
public T getValue(String p) throws Exception {
return clazz.getConstructor(String.class).newInstance(p);
}
}
Beware: reflection is slow.
Not *that* slow. Granted, slower than normal object instantiation, but
every Java release they seem to enhance the speed of reflection.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>