Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object vs Class<T> (vs Class<?>?) in java?

Tags:

java

generics

I'm very new to Java. This is probably a stupid question--but i can't find the answer anywhere. If you wanted to declare a method that would take in an unknown object and do something with it (copy it, for example), what would be the difference between something like:

<T> T func(Class<T> cls){
    //do something
}

Object func(Object o){
    //do something 
}

Are they comparable? Is there anything you could/would do with one of the above methods and not the other? And where does Class<?> fit in?

like image 691
user3771823 Avatar asked Jun 24 '14 15:06

user3771823


1 Answers

The difference in your code is that former func receives a Class<T> (which can be Class<?>) which means the method only receives a Class type . The latter receives any object, regardless if it's a class or another kind of object.

From Class javadoc:

Instances of the class Class represent classes and interfaces in a running Java application. An enum is a kind of class and an annotation is a kind of interface. Every array also belongs to a class that is reflected as a Class object that is shared by all arrays with the same element type and number of dimensions.

Note that Class is metadata for your classes.


If your code were like this:

<T> T func(T o){
    //do something
}

Object func(Object o){
    //do something 
}

The main difference is the return type: the former return type should be as the same type of the argument, while the latter is a generic Object. For example:

Object func(Object o){
    //do something 
    return o.toString(); //compiles and works
}
<T> T func(T o){
    //do something
    return o.toString(); //does not compile
}
like image 119
Luiggi Mendoza Avatar answered Oct 26 '22 02:10

Luiggi Mendoza