Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java generic methods cast to parameter type at runtime, is it possible?

I have a method that looks like this

 public static <T extends MyClass, X extends AnotherClass> List<T> (Class<T> aParameter, X anotherParameter)

Now if AnotherClass is an abstract class that does NOT Have getId defined, but every single class that extends this interface does. (Don't ask me why it is designed this why, I did not design the abstract class, and I am not allowed to change it).

How can I do something like this

anotherParameter.getId();

I know I have to cast it to the class, but then i have to do an instanceof check for every possible class and then cast it.

So right know i have something like:

if (anotherParameter instanceof SomeClass)
    ((SomeClass)anotherParameter).getId();  //This looks bad.

Is it possible to cast this dynamically?, to whatever anotherParameter is at runtime?.

like image 446
Oscar Gomez Avatar asked Dec 12 '22 19:12

Oscar Gomez


1 Answers

Can you modify derived classes? If so, you could define an interface for this (syntax maybe wrong):

public interface WithId {
    void getId();
}
...
public class MyDerivedClass1 extends AnotherClass implements WithId {
...
}
...
public class MyDerivedClass2 extends AnotherClass implements WithId {
...
}

and then, inside your method do:

...
if (anotherParameter instanceof WithId) {
 WithId withId = (WithId) anotherParameter;
 withId.getId();
}
...

If you can change your method's signature, maybe you can specify an intersection type:

public static <T extends MyClass, X extends AnotherClass & WithId> List<T> myMethod(Class<T> aParameter, X anotherParameter)

and then you would have getId() available directly inside your method.

like image 174
gpeche Avatar answered May 10 '23 10:05

gpeche