简体   繁体   中英

As a method parameter in Java, what does the question mark allow you to do in Class<?>

With the code segment below what does the question mark allow you to do, since it is in angle brackets by a class type? Does it allow for any class type to be passed in as a parameter?

Also, what does method 1 return? Does it return an object that can be cast to an ObjectService type?

method 1

public Object getInstance(Class<?> clazz) {
    if (org.service.ObjectService.class.equals(clazz))
        return getObjectService();
    return null;
}

method 2

public ObjectService getObjectService() {
    ObjectService service;

    service = (ObjectService) context.getBean("ObjectService");

    return service;
}

It tells the compiler to accept any type of Class as a parameter. Basically, this way you choose to turn off compiler's type check. Alternatively, you can omit <?> altogether with a compiler warning or do as Luiggi suggested and specify Class<Object> , which is not always the same though.

If your generic class is defined with restrictions, <Object> would not be an acceptable parameter.

For instance, if you have the following class somewhere:

public class TheClass<T extends Component> {
}

You can't do TheClass<Object> . You can do TheClass<Component> or TheClass<?> , which are essentially the same for TheClass case.


UPDATE TO ANSWER UPDATED QUESTION

getInstance() in your case will defer to getObjectService(), which can only return ObjectService. You're guaranteed to receive one of the following:

  • ObjectService instance.
  • null.
  • ClassCastException from method getObjectService(), where casting is performed.

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