user3786942
user3786942

Reputation: 163

Why passing .class name in constructor function in Java

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

Answers (3)

Scott N
Scott N

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

Patrick Collins
Patrick Collins

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

David Xu
David Xu

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

Related Questions