0

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 id) {
    return classObject.newInstance();
}

public static void main(String[] args) {
    MyEntity entity = MyClass.findStuff(MyEntity.class, "abc");
}

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

2 Comments

MByD: Sorry, my bad earlier post. I've updated my post again. Thank you !
@Albert Kam - I think you can't do it as you describe, but the guy below will probably give you a certain answer in a few minutes :)
2

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 :(

2 Comments

Jon Skeet: Sorry for the post that doesnt describe my problem. I've updated my post again. Thank you !
Jon Skeet: Ah, i dont really understand yet, but will take a look into it. I was thinking something like what is available for parameterized class, like doing the getClass().getGenericSuperClass().getActualTypeArguments. Thank you.
1
// because object extends java.lang.Object
Class<?> classObject = object.getClass(); 

1 Comment

MarvinLabs: Sorry, wrong example in my previous post. I've updated my post again. Thank you !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.