如果两个类有一些完全相同的签名方法,但这些方法不是继承的,那么是否有任何方法可以使用公共方法定义接口,并使用相同的接口指向两个类的两个实例?
例如,假设一个类Cat有boolean isAlive(),另一个类Dog有boolean isAlive(),但是Cat和Dog除了Object没有共同祖先,boolean isAlive()不是继承的方法。我不能修改Cat或Dog,因为它们是由其他人编写的。我可以任意创建这样的接口并使用它来指向猫或狗吗?
interface lovable
{
boolean isAlive();
}
void main()
{
lovable thing = new Cat(); <-- any syntax to achieve this?
love(thing);
}
void love(lovable thing)
{
if (thing.isAlive())
System.out.println("Aww.");
else
System.out.println("Eww.");
}发布于 2016-02-26 16:17:01
可以像Can you force a java object into implementing an interface at runtime?中提到的那样创建代理对象:
public interface Loveable {
boolean isAlive();
}
public static class Cat {
boolean isAlive() {
return true;
}
}
public static class Dog {
boolean isAlive() {
return false;
}
}
public static <T> T getWrapper(final Object obj, final Class<T> intface) {
InvocationHandler invocationHandler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
return obj.getClass().getDeclaredMethod(method.getName(), method.getParameterTypes()).invoke(obj, args);
}
};
return (T) Proxy.newProxyInstance(obj.getClass().getClassLoader(), new Class[]{intface}, invocationHandler);
}
public static void main(String[] args) throws Exception {
System.out.println(getWrapper(new Cat(), Loveable.class).isAlive());
System.out.println(getWrapper(new Dog(), Loveable.class).isAlive());
}发布于 2016-02-26 16:04:41
如果你自己创造的话:
public interface Lovable{
boolean isAlive();
}
public class LovableCat extends Cat implements Lovable{
}public static void main() {
Lovable thing = new LovableCat();
love(thing);
}如果从其他地方返回:
public interface Lovable{
boolean isAlive();
}
public class LovableCat implements Lovable{
private Cat cat;
public LovableCat(Cat cat){
this.cat = cat;
}
public boolean isAlive(){
return cat.isAlive();
}
}public static void main() {
Lovable thing = new LovableCat(cat);
love(thing);
}发布于 2016-02-26 16:22:33
您不能这样做,因为您的类型(猫,狗)必须实现您的接口。但是,如果这个类来自某个库,那么您将有两个解决方案。前面提到的第一个使用包装器,第二个使用反射。我认为lib www.eclipse.org/aspectj可以帮助您以最少的代价实现这一点。
https://stackoverflow.com/questions/35655958
复制相似问题