简体   繁体   中英

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);

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[] .

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;
    }
}

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM