簡體   English   中英

Object.class / object.getClass()(有什么區別)

[英]Object.class/object.getClass() (what is the difference)

Customer.classcust.getClass() 工作,但是 cust.class不可以 嗎? 有什么區別?

public class Customer() {

}


public class Test {

    public Test() {
        Customer cust = new Customer();

        test(Customer.class);
        test(cust.getClass());
    }


    public <T> void test(Class<T> clazz) {
        System.out.println(clazz);
    }

}

Object.class是Object的“偽靜態字段”,並返回命名類的類對象。 它基本上生成零代碼。

obj.getClass()是Object的虛擬方法,並在obj引用中返回該對象的ACTUAL類對象。 它生成一個實際的調用來檢查和檢索該類(該類可能是引用的聲明類的子類)。

我不確定obj.class是否會編譯,但是如果這樣做,則相當於“編譯器混亂”,等效於對Object.class進行編碼-通常,當您使用引用代替文字類名稱時,會得到等效的結果就像您已編碼引用的聲明的類名一樣。

構造obj.class根本不會編譯,因為.class僅適用於類。 像String.class一樣,對於類的實例,您需要調用getClass()

OP更改后進行編輯

讓我們重做示例:

public class Test {

    public static void main (String[] args){
        Test t = new Test();
    }

    public Test() {
        Customer customer = new FastFoodCustomer();
        test(Customer.class); 
        test(customer.getClass());
    }


    public <T> void test(Class<T> clazz) {
        System.out.println(clazz);
    }

}

class Customer{

}

class FastFoodCustomer extends Customer{

}

這給出以下輸出:

class Customer
class FastFoodCustomer

getClass()方法是從Object祖先類繼承的。 它將告訴您對象是什么類。 如果您想知道給定的實例類,則需要調用thatInstance.getClass()方法。 如果您致電Customer.class您將獲得class Customer因為您正在詢問Customer是什么類。 但是對象Customer既可以是Customer ,也可以是它的任何子類(在此示例中為FastFoodCustomer)。

您的另一個示例cust.class不起作用,因為cust本身沒有繼承的任何class屬性。

Object class具有對Object class的引用,但是obj具有對實例的引用,因此應使用obj.getClass()方法

PS:如果投票失敗,請讓我知道我的錯在哪里。

暫無
暫無

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

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