java 用反射 获得泛型

public static void main(String[] args) throws Exception {
		class Address{
			public String getValue(){
				System.out.println("haha  generic");
				return null;
			}
		}
		
		class User{
			private List<Address> address;
			
			public List<Address> getAddress() {
				return address;
			}
			public void setAddress(List<Address> address) {
				this.address = address;
			}
			
			
		}
		Field[] fields=User.class.getDeclaredFields();
		for(Field field:fields){
			Type type=field.getGenericType();
			System.out.println(type.toString());

				if(type instanceof ParameterizedType) // 如果是泛型参数的类型 
				{ 
				ParameterizedType pt = (ParameterizedType) type;

				Class genericClazz = (Class)pt.getActualTypeArguments()[0]; // 得到泛型里的class类型对象。

				System.out.println(field.getName());
				Object o=genericClazz.newInstance();
				Address a=(Address)o;
				System.out.println(a.getValue());
				
				} 
		}
		
	}

你可能感兴趣的:(java)