在Java中的方法中传递和使用Class [英] Passing and using Class in a method in Java
本文介绍了在Java中的方法中传递和使用Class的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
void methodA() {
methodB(ClassA.class)
}
void methodB(Class classname) {
classname a; //not correct
HashMap<String, classname> hash = new HashMap<>(); //not correct
}
IDE抱怨它不正确。
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?
推荐答案
不能使用变量名称作为类型名称, code> methodB 将无法编译。
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<>();
}
这篇关于在Java中的方法中传递和使用Class的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文