Reputation: 163
I have seen so many Java code examples passing *.class as a parameter to the constructor function. Why would I do that? When would I do that?
For ex.:
ServletHolder sh = new ServletHolder(ServletContainer.class);
Upvotes: 0
Views: 1192
Reputation: 71
The constructor is obviously looking for a class object, but I think you might be asking a deeper question as to why an instance of one class would like to know about a different class. There are many reasons for this, but they mostly revolve around reflection. Reflection allows a program to inspect the structure of a class, it's constructors, methods, interfaces, etc by name, and then be able to call them.
Upvotes: 1
Reputation: 10574
T.class
has the type Class<T>
. It gives you access to the class itself as an object. The Oracle docs have a number of different examples of how you can get a Class<T>
object.
They're generally used with reflection to do some meta-manipulation on the class itself. There's an SO thread with some examples.
For example, I might define a Logger
object that takes a Class<T>
as a parameter. Then it could do things like:
class LoggerForClass<T> {
String className;
public LoggerForClass(Class<T> klass) {
className = klass.getName();
}
public String log(String message) {
return className + ": " + message;
}
}
Upvotes: 1
Reputation: 5597
Usually this is used to allow Reflection in Java to create concrete versions of the class passed in. For example, Arrays.copyOfRange(...)
has an overload that takes a class parameter to return an actual Array typed with the Class[] that is passed into the method.
Without the parameter, it will return an Object[]
. With the parameter, it will return an array like this, for example, SomeClass[]
.
Upvotes: 3