Ava
Ava

Reputation: 6043

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?

Upvotes: 0

Views: 99

Answers (2)

Sreekumar
Sreekumar

Reputation: 47

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

Upvotes: 0

rgettman
rgettman

Reputation: 178243

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

Upvotes: 3

Related Questions