簡體   English   中英

如何將變量的名稱及其在 Java 中的類型作為輸出獲取?

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

我有以下課程:

public class Example {

    private String name;
    private int year;

    public Example() {

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

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

想象一下,在主類中,我創建了前一個類( Example )的對象並執行它的構造函數。 然后我想執行showData()並且我想看到以下輸出(給定這個例子):

String name Clifford the big red dog
int year 2020

主要看起來像這樣:

public static void main () {

    Example example = new Example();

    example.showData();
}

有什么辦法可以做到這一點嗎?

請按以下步驟操作:

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();
    }
}

輸出:

String name Clifford the big red dog
Integer year 2020

然而,由於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();
    }
}

輸出:

String name Clifford the big red dog
int year 2020

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM