简体   繁体   中英

Passing and using Class in a method in Java

void methodA() {
  methodB(ClassA.class)
}

void methodB(Class classname) {
  classname a; //not correct
  HashMap<String, classname> hash = new HashMap<>(); //not correct
}

IDE is complaining it to be not correct.

I want to do something like what is being commented as //not correct. Why is it not correct and how can I do it?

You cannot use a variable name as a type name, so methodB won't compile.

You can however use a type parameter for the method. Try

<T> void methodB(Class<T> clazz) {
    T a;
    HashMap<String, T> hash = new HashMap<>();
}

You can't use variable name as type of any method that has to passed as parameter. Else it will give compilation error.

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