Customer.class
and cust.getClass()
work, but
? What is the difference? cust.class
does not
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
is a "pseudo static field" of Object and returns the class object for the named class. It generates essentially zero code.
obj.getClass()
is a virtual method of Object and returns the ACTUAL class object for the object in the obj
reference. It generates an actual call to inspect and retrieve the class (which may be a subclass of the reference's declared class).
I'm not sure if obj.class
will compile, but if it does it's a "compiler swizzle" equivalent to coding Object.class
-- in general, when you use a reference in place of a literal class name, you get the equivalent as if you'd coded the reference's declared class name.
Construction obj.class will not compile at all, because .class will works only for classes. Like String.class, for instances of class you need to call getClass()
Edited after OP changes
Let's redo the example:
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{
}
This gives the following output:
class Customer
class FastFoodCustomer
getClass()
method is inherited from Object
ancestor class. It will tell you what class the object is. If you want to know a given instance class you need to call thatInstance.getClass()
method. If you call Customer.class
you are getting just class Customer
because you are asking what class Customer
is. But an object Customer
can be a Customer
but also it can be any subclass of it (ie FastFoodCustomer in this example).
Your other example cust.class
doesn't work because cust
doesn't have any class
attribute by itself nor inherited.
Object class
has a reference to a class, but obj
has the reference to an instance only, so you should use the method obj.getClass()
PS: If downvoting, please let me know where is my fault.
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.