java - 是否可以将接口(interface)类型转换为值?

标签 java interface casting anonymous-types

我有一个界面:

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/

相关文章:

spring - 如何在 Spring 表达式语言中进行类型转换

java - lucene index getDocCount() 返回的值与总输入文档数不同

go - 试图将文字转换为 Golang 中的指针

java - 类型转换和泛型,有什么性能差异?

python - 覆盖 __class__ 引发 TypeError

delphi - 如何在 Delphi 中找到导致 AV 的悬空接口(interface)

java - 在内存中存储等距网格的最佳方法是什么?

java - 仅通过一个 SocketChannel 发送多条消息

java - 识别 docx 中文本的颜色

c# - 为什么 Dictionary<TKey, TValue> 没有采用 KeyValuePair 对象的 Add 方法?