问题描述
在Java中有没有反映局部变量类型的方法?我知道你用这个字段来解决这个问题 - 。任何想法如何解决,例如:
public void foo(List< String> s){
//反映s以某种方式得到弦乐
}
甚至更一般:
public void foo< T>(List< T>){
//反映s以某种方式获得T
}
是一个很好的教程,它展示了如何以及何时使用反射读取泛型。例如,从你的冷杉中得到字符串 foo
方法
public void foo (List< String> s){
// ..
}
你可以使用这段代码
class MyClass {
public static void foo(List< String> s ){
// ..
}
public static void main(String [] args)throws Exception {
Method method = MyClass.class.getMethod( foo,List.class);
类型[] genericParameterTypes = method.getGenericParameterTypes(); (类型genericParameterType:genericParameterTypes){
if(genericParameterType instanceof ParameterizedType){
ParameterizedType aType =(ParameterizedType)genericParameterType;
$ b $
类型[] parameterArgTypes = aType.getActualTypeArguments();
for(类型parameterArgType:parameterArgTypes){
Class parameterArgClass =(Class)parameterArgType;
System.out.println(parameterArgClass =
+ parameterArgClass);
}
}
}
}
}
输出: parameterArgClass = class java.lang.String
$ b 这是可能的,因为您在源代码中显式声明List可以包含只有字符串。但是,如果
公共< T> void foo2(List< T> s){
//反映s以某种方式得到T
}
T可以是任何类型,因为类型擦除,不可能检索关于精确T类的信息。
Is there a way in Java to reflect a generic type of a local variable? I know you sould to that with a field - Get generic type of java.util.List. Any idea how to solve, for instance:
public void foo(List<String> s){
//reflect s somehow to get String
}
Or even more general:
public void foo<T>(List<T> s){
//reflect s somehow to get T
}
Here is nice tutorial that shows how and when you can read generic types using reflection. For example to get String from your firs foo
method
public void foo(List<String> s) {
// ..
}
you can use this code
class MyClass {
public static void foo(List<String> s) {
// ..
}
public static void main(String[] args) throws Exception {
Method method = MyClass.class.getMethod("foo", List.class);
Type[] genericParameterTypes = method.getGenericParameterTypes();
for (Type genericParameterType : genericParameterTypes) {
if (genericParameterType instanceof ParameterizedType) {
ParameterizedType aType = (ParameterizedType) genericParameterType;
Type[] parameterArgTypes = aType.getActualTypeArguments();
for (Type parameterArgType : parameterArgTypes) {
Class parameterArgClass = (Class) parameterArgType;
System.out.println("parameterArgClass = "
+ parameterArgClass);
}
}
}
}
}
Output: parameterArgClass = class java.lang.String
It was possible because your explicitly declared in source code that List can contains only Strings. However in case
public <T> void foo2(List<T> s){
//reflect s somehow to get T
}
T can be anything so because of type erasure it is impossible to retrieve info about precise T class.
这篇关于运行时局部变量的通用类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!