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?.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With