Sam
Sam

Reputation: 31

How to cast an object to a class being passed in as a parameter at runtime?

I am trying to write a piece of code that takes a class that extends another class as a parameter, and then casts an object of that superclass already defined in the method to the class being passed in.

Here's an example of what I've tried so far. It's simplified because I've got a lot of other code in the method.

public <E extends Resource> Resource createResource(Class<E> res) {
    Resource resourceObject = res.getDeclaredConstructor().newInstance();

    // This requires a cast, is it possible to cast it to the res class and not a "User" class
    resourceObject.setEmail("[email protected]");

    return resourceObject;
}

But the problem is when I print out the resourceObject object, it knows that it is a User object (which is being passed in as the class parameter).

Upvotes: 0

Views: 210

Answers (1)

Don't pass in Class<E> res; instead, pass Supplier<E> supplier. This avoids reflection (and possible exceptions), doesn't necessarily require a zero-arg constructor, and ensures that you get a politely typed result. For the cases where you do want to say "call the no-arg constructor", supply User::new.

Upvotes: 1

Related Questions