Java getClass().getName() 它返回类而不是名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21666026/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:57:23  来源:igfitidea点击:

Java getClass().getName() it returns the class not the name

java

提问by user3290793

The output was Card Card. It was suppose to be unknown Jane. How do i fix this? I tried to fix it with Card.getClass().getName() but that gives me another error non-static method getClass() cannot be referenced from a static context.

输出是 Card Card。估计是不认识的简。我该如何解决?我试图用 Card.getClass().getName() 修复它,但这给了我另一个错误非静态方法 getClass() 不能从静态上下文中引用。

public class Card

{
    private String name;

    public Card()
    {
        name = "unknown";
    }

    public Card(String name1)
    {
        name = name1 ;
    }

    public String getName()
    {
        return name;
    }

    public String toString()
    {
        return getClass().getName();
    }
}

public class CardTester
{
    public static void main(String[] args)
    {
        Card card ;

        card = new Card() ;
        System.out.println(card) ;
        System.out.println("unknown WAS EXPECTED") ;

        card = new Card("Jane") ;
        System.out.println(card) ;
        System.out.println("Jane WAS EXPECTED") ;
    }
}

采纳答案by user2864740

getClass()returns the Class objectrepresenting the "Card" class; therefore the code does notrefer to Card#getNamemethod, but rather to Class#getNamewhich dutifully returns "Card".

getClass()返回表示“卡片”类的Class 对象;因此,代码不是Card#getName方法,而是Class#getName指尽职尽责地返回“卡片”的方法。

Simply remove getClass():

只需删除getClass()

public String toString()
{
    return getName();
}

The previous error (wrt "static") was using Card.getName()- don't prefix a typeto invoke an instancemethod.

上一个错误(wrt "static")正在使用Card.getName()- 不要为类型添加前缀来调用实例方法。

回答by JB Nizet

Your toString()method prints the name of the class of the object:

您的toString()方法打印对象的类的名称:

return getClass().getName();

The object is an instance of Card, so its class is Card.class, whose name is Card. You want to print the value of the name field. So you simply need

该对象是 的一个实例Card,因此它的类是Card.class,其名称是Card。您想打印名称字段的值。所以你只需要

return name;