我有一个界面:
public interface TestFace {
public String outThis();
}
具有参数为接口(interface)类型的方法的类:
class MyClass {
public void outMeth(TestFace inMeth){
System.out.print(inMeth); //the method attempts to print the interface type
}
}
如果我像这样调用对象的方法:
MyClass a = new MyClass();
a.outMeth(new TestFace() {
public String outThis() {
String val = "something";
return val;
}
});
打印的值是对实例的引用。有人可以解释为什么会发生这种情况/如何正确执行此操作吗?
最佳答案
对 Object
执行 System.out.println
的结果始终是调用该对象的 toString()
方法的结果。如果您从 Object
继承它(通过不编写显式 toString()
),您将获得默认的 Object
实现,指定为:
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '@' + Integer.toHexString(hashCode())
匿名类的“名称”通常反射(reflect)了定义该匿名类的类,通常在末尾添加 $1
等。
如果您想要一个更有用的 toString()
,请重写它并自己编写一个:
new TestFace() {
public String outie() {
String val = "something";
return val;
}
public String toString() {
return outie();
}
}
关于java - 是否可以将接口(interface)类型转换为值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36095080/