简体   繁体   中英

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. Then I want to execute showData() and I would like to see the following output (given this example):

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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