Gle*_*son 4 java casting duck-typing interface
有时在Java中,有一种情况是你使用一个提供a的库,final class Car
你希望它实现一些Vehicle
接口,这样你就可以在代码中制作Truck
和Bus
分类并将它们全部视为Vehicle.但Car是最终的,它没有实现任何接口.
如何将其他人的最终Car
课程投射到我的Vehicle
界面,以便我可以像其他车辆一样传递它?在实例方法名称,参数类型和返回类型方面,Vehicle上的每个实例方法都与Car上的类似方法100%兼容.从Duck-Typing的角度来看,它将是相同的.
我知道我可以创建一个MyCar extends Vehicle
包装类,它只是将每个方法调用委托给内部Car对象.这将是The Java Way.但我只是想知道是否有一种技术可以将一个类实际转换为不相关(但100%兼容)的接口.如果答案是邪恶的,那就没关系.
用代理做:
import java.lang.reflect.Proxy;
public class DuckTyping {
static final class Car{
public void honk(){
System.out.println("honk");
}
}
interface Vehicle{
void honk();
}
public static void main(String[] a){
Car c = new Car();
Vehicle v = (Vehicle) Proxy.newProxyInstance(Vehicle.class.getClassLoader(), new Class[]{Vehicle.class}, (proxy, method, args) ->
Car.class.getMethod(method.getName(), method.getParameterTypes()).invoke(c, args)
);
v.honk();
}
}
Run Code Online (Sandbox Code Playgroud)
通用方法:
static <T> T proxyCast(Object targetObject, Class<T> targetClass) {
return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class[]{targetClass}, (proxy, method, args) ->
targetObject.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(targetObject, args)
);
}
Run Code Online (Sandbox Code Playgroud)
Azo*_*qua -1
正如您所提到的,我个人会为其创建一个包装类。
也许对接口的引用Car
会有帮助?
public abstract class MyCar implements Vehicle {
private Car car;
(...)
}
Run Code Online (Sandbox Code Playgroud)
没有太多方法可以做到这一点,我不确定我的方法是你想要的,也不确定它是否完全有效。