gpt4 book ai didi

java - 将未实现的接口(interface)转换为对象

转载 作者:行者123 更新时间:2023-11-30 10:05:46 24 4
gpt4 key购买 nike

我有一个实现了与接口(interface)相同方法的类

public class MyClass {

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

这是接口(interface)定义-

public interface MyInterface {

String getString(final String stringName);
}

是否可以将接口(interface)转换为类对象-

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

最佳答案

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

但是你可以使用java-8的方法引用将你在MyClassgetString中实现的逻辑传递给接口(interface)引用类型:

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"));
}

此外,您不能像在代码中那样实例化接口(interface)。

关于java - 将未实现的接口(interface)转换为对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55085655/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com