Osc*_*mez 4 java generics types casting runtime
我有一个看起来像这样的方法
public static <T extends MyClass, X extends AnotherClass> List<T> (Class<T> aParameter, X anotherParameter)
Run Code Online (Sandbox Code Playgroud)
现在,如果AnotherClass是一个没有定义getId的抽象类,但扩展此接口的每个类都有.(不要问我为什么设计这个为什么,我没有设计抽象类,我不允许改变它).
我怎么能做这样的事情
anotherParameter.getId();
Run Code Online (Sandbox Code Playgroud)
我知道我必须将它投射到课堂上,但是我必须对每个可能的课程进行一次检查,然后再进行投射.
所以我知道我有类似的东西:
if (anotherParameter instanceof SomeClass)
((SomeClass)anotherParameter).getId(); //This looks bad.
Run Code Online (Sandbox Code Playgroud)
是否可以动态地将其转换为运行时的其他参数?
你能修改派生类吗?如果是这样,你可以为此定义一个接口(语法可能错误):
public interface WithId { void getId(); } ... public class MyDerivedClass1 extends AnotherClass implements WithId { ... } ... public class MyDerivedClass2 extends AnotherClass implements WithId { ... }
然后,在你的方法里面做:
... if (anotherParameter instanceof WithId) { WithId withId = (WithId) anotherParameter; withId.getId(); } ...
如果您可以更改方法的签名,也许您可以指定交集类型:
public static <T extends MyClass, X extends AnotherClass & WithId> List<T> myMethod(Class<T> aParameter, X anotherParameter)
然后你getId()
可以在你的方法中直接使用.