有时在 Java 中,有这样一种情况,您使用一个提供 final class Car
的库,并且您希望它实现一些 Vehicle
接口(interface),这样您就可以制作 Truck
和 Bus
类,并在您的代码中将它们全部视为 Vehicles。但是 Car 是最终的,它没有实现任何接口(interface)。
如何将其他人的最终 Car
类转换为我的 Vehicle
接口(interface),以便我可以像其他 Vehicle 一样传递它? Vehicle 上的每个实例方法在实例方法名称、参数类型和返回类型方面都与 Car 上的类似方法 100% 兼容。从 Duck-Typing 的角度来看,这将是等效的。
我知道我可以创建一个 MyCar extends Vehicle
包装类,它只将每个方法调用委托(delegate)给一个内部 Car 对象。这就是 Java 之道。但我只是想知道是否有一种技术可以将一个类实际转换为不相关(但 100% 兼容)的接口(interface)。如果答案是邪恶的也没关系。
最佳答案
用代理做:
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();
}
}
通用方法:
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)
);
}
关于java - 将最终类转换为该类未声明实现的兼容接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36094950/