简体   繁体   English

如何将变量的名称及其在 Java 中的类型作为输出获取?

[英]How can I get as an output the name of a variable and it's type in Java?

I have the following class:我有以下课程:

public class Example {

    private String name;
    private int year;

    public Example() {

        name = "Clifford the big red dog";
        year = 2020;
    }

    public void showData() {
        // ?????
    }
}

Imagine in the main class I create an object of the previous class ( Example ) and execute it's constructor.想象一下,在主类中,我创建了前一个类( Example )的对象并执行它的构造函数。 Then I want to execute showData() and I would like to see the following output (given this example):然后我想执行showData()并且我想看到以下输出(给定这个例子):

String name Clifford the big red dog
int year 2020

The main would look like this:主要看起来像这样:

public static void main () {

    Example example = new Example();

    example.showData();
}

Is there any way I can do this?有什么办法可以做到这一点吗?

Do it as follows:请按以下步骤操作:

class Example {

    private String name;
    private int year;

    public Example() {

        name = "Clifford the big red dog";
        year = 2020;
    }

    public void showData() {
        System.out.println(name.getClass().getSimpleName() + " name " + name);
        System.out.println(((Object) year).getClass().getSimpleName() + " year " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Example example = new Example();
        example.showData();
    }
}

Output:输出:

String name Clifford the big red dog
Integer year 2020

However, since showData is a method of class Example which already knows about its instance variables, you can simply do it as:然而,由于showDataclass Example一个方法,它已经知道它的实例变量,你可以简单地这样做:

class Example {

    private String name;
    private int year;

    public Example() {

        name = "Clifford the big red dog";
        year = 2020;
    }

    public void showData() {
        System.out.println("String name " + name);
        System.out.println("int year " + year);
    }
}

public class Main {
    public static void main(String[] args) {
        Example example = new Example();
        example.showData();
    }
}

Output:输出:

String name Clifford the big red dog
int year 2020

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM