java 放射的用法

package com.wonlymall.mall.modular.user.modelVO;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.springframework.stereotype.Component;

public class TestReflect {

public static void main(String[] args) {
	//获取具体类的类型
	Class<?>clazz=UserBaseInfoVO.class;
	Object obj=new Object();
	//获取Object 类的类型
	Class clazz1=obj.getClass();
	//获取类名
	String className=clazz.getName();
	System.out.println(className);
	//获取类的注解
	Component c=clazz.getAnnotation(Component.class);
	System.out.println(c);
	//获取注解的参数值
	String value=c.value();
	System.out.println(value);
	//获取类上面的注解
	Component c1=clazz.getAnnotationsByType(Component.class)[0];
	//获取本类的所有注解
	Annotation[]a=clazz.getDeclaredAnnotations();
	Annotation[]a1=clazz.getAnnotations();
	try {
		//根据放射获取构造器  利用构造器创建对象
		//Constructor constructor=clazz.getConstructor(Integer.class);
		//UserBaseInfoVO vo=(UserBaseInfoVO) constructor.newInstance(1121);
		//System.out.println(vo.getEscOrgId());
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} 
	//获取本类中的所有构造器
	Constructor[]con=clazz.getDeclaredConstructors();
	System.out.println(con);
	//获取父类
	Class superClazz=clazz.getSuperclass();
	System.out.println(superClazz);
	Method[]method=clazz.getDeclaredMethods();
	System.out.println(method);
	try {
		UserBaseInfoVO vo=(UserBaseInfoVO) clazz.newInstance();
		Field field=clazz.getDeclaredField("escOrgId");
		//获取属性上面的注解
		//field.getAnnotation(annotationClass)
		//获取参数类型
		//field.getGenericType().toString();
		field.setAccessible(true);
		field.set(vo, 111);
		System.out.println(vo.getEscOrgId());
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	//获取类的所有属性
	//Field[]fields=clazz.getDeclaredFields();
	//for(Field f:fields) {
		//String fieldName=f.getName();
		//System.out.println(f.getName());
	//}
	//Field[]fields=clazz.getSuperclass().getFields();
	//for(Field f:fields) {
		//String fieldName=f.getName();
		//System.out.println(f.getName());
	//}
}

}

猜你喜欢

转载自blog.csdn.net/weixin_39522272/article/details/88533649
今日推荐