问题
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