I have a simple static method :
public static <U> U findStuff(String id) {
// how can i get the class of type U here ?
Class classObject = ....;
return classObject.newInstance();
}
public static void main(String[] args) {
MyEntity entity = MyClass.<MyEntity>findStuff("abc");
}
I wonder how i can get the class object from the U ?
Currently i have to pass the class around because i dont know the way yet.. so, now im using something like this :
public static <U> U findStuff(Class<U> classObject, String i开发者_高级运维d) {
return classObject.newInstance();
}
public static void main(String[] args) {
MyEntity entity = MyClass.findStuff(MyEntity.class, "abc");
}
To get the class of the object, use object.getClass();
By the way, this is a common way to do it that is not related to Generics
Does
Class<?> classObject = object.getClass();
do enough for you? It's not clear what you need em.find
to do.
EDIT: Okay, with the edit, you're running into the problem of type erasure. Basically, you need to pass in the class you're interested in, as you're already doing. See the Java generics FAQ for more information. It's an unfortunate corollary of the way that Java generics are implemented :(
// because object extends java.lang.Object
Class<?> classObject = object.getClass();
精彩评论