java反射的高級應用

public class DemoClass {
         //獲取String對應的class
	private List<String> hobby ;
	//獲取Comparable<?> class類型
	private List<? extends Comparable<?>> compareableList;
	
	
	public static void main(String[] args) throws NoSuchFieldException, SecurityException {
//		getListParameterType();
//		getWildcardTypeMethod1();
	}


	private static void getWildcardTypeMethod1() throws NoSuchFieldException {
		Field field = DemoClass.class.getDeclaredField("compareableList");
		ParameterizedType genericType = (ParameterizedType) field.getGenericType();
		Type[] actualTypeArguments = genericType.getActualTypeArguments();
		WildcardType wildcardType = (WildcardType) actualTypeArguments[0];
		System.out.println(wildcardType.getUpperBounds()[0]);
	}

	private static void getListParameterType() throws NoSuchFieldException {
		Field field = DemoClass.class.getDeclaredField("hobby");
		
		ParameterizedType genericType = (ParameterizedType) field.getGenericType();
		System.out.println(field.getGenericType());
		Type[] actualTypeArguments = genericType.getActualTypeArguments();
		System.out.println(actualTypeArguments[0]);
	}
}

// 獲取T對應的類型
public static class Bar extends Foo<T> {
  public Class<?> getParameterClass() {
    return (Class<?>) (((ParameterizedType)Bar.class.getGenericSuperclass()).getActualTypeArguments()[0]);
  }
}
相關文章
相關標籤/搜索