Passing and using Class in a method in Java

走远了吗. 提交于 2019-12-13 21:18:15

问题


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?


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/27413112/passing-and-using-class-in-a-method-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!