0
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?

0

2 Answers 2

3

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<>();
}
Sign up to request clarification or add additional context in comments.

4 Comments

methodB(ClassA.class) will still be the same? T is red. It asks me to create class T. Why is there a <T> before void methodB?
Yes, you can still pass in ClassA.class. It will control what type T is inferred to be.
The <T> declares a generic type parameter for the method, making T in scope for the method. This should work for Java 1.5+ (when generics were introduced).
When you call methodB, pass ClassA.class as an argument to methodB. In methodB, the parameter clazz is assigned the value passed in - ClassA.class.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.