Java,我可以将任意接口应用于现有类吗?

Dam*_*les 3 java interface

如果两个类有一些签名完全相同的方法,但这些方法没有被继承,有没有办法用公共方法定义一个接口,并使用相同的接口指向两个类的两个实例?

例如,假设一类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.");
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 6

您可以创建代理对象,如您能否在运行时强制 java 对象实现接口?:

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());
}
Run Code Online (Sandbox Code Playgroud)


Ken*_*kov 5

如果您自己创建它:

public interface Lovable{
    boolean isAlive();
}

public class LovableCat extends Cat implements Lovable{

}
Run Code Online (Sandbox Code Playgroud)
public static void main() {
    Lovable thing = new LovableCat();
    love(thing);
}
Run Code Online (Sandbox Code Playgroud)

如果从其他地方返回:

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();
    }
}
Run Code Online (Sandbox Code Playgroud)
public static void main() {
    Lovable thing = new LovableCat(cat);
    love(thing);
}
Run Code Online (Sandbox Code Playgroud)

  • 好奇:为什么不是`public class LovableCat extends Cat implements Lovable`? (2认同)