将未实现的接口强制转换为对象

时间:2019-03-10 07:59:43

标签: java casting

我有一个使用与接口相同的方法的类

public class MyClass {

String getString(final String stringName) {
//doSomething
    };
}

这是接口定义-

public interface MyInterface {

String getString(final String stringName);
}

是否可以将接口强制转换为类对象-

MyInterface interace = new MyInterface;
MyClass class = (Myclass) interface;

1 个答案:

答案 0 :(得分:1)

无法将未实现的类对象强制转换为接口类型,因为在运行时会得到ClassCastException。这是因为Java不支持duck typing,它不检查方法签名是否相同。

但是您可以使用java-8 方法引用将在MyClass getString中实现的逻辑传递给接口引用类型:

class MyClass {
    String getString(final String stringName) {
        return stringName;
    }
}
interface MyInterface {
    String getString(final String stringName);
}

public static void main(String[] args) {
    //MyInterface  myInterface = (MyInterface)new MyClass(); //java.lang.ClassCastException: class MyClass cannot be cast to class MyInterface
    MyClass clazz = new MyClass();
    MyInterface  myInterface = clazz::getString;
    System.out.println(myInterface.getString("test"));
}

此外,您无法像在代码中那样实例化接口。

相关问题