码迷,mamicode.com
首页 > 编程语言 > 详细

java的反射基础入门

时间:2018-07-14 23:37:23      阅读:348      评论:0      收藏:0      [点我收藏+]

标签:getbean   cto   oid   intro   retention   name   param   tar   array   

1.获取反射Class类的方式

Class.forName("全类名");

类名.class//需要在JVM已加载的前提下

对象.getClass

2.java对javabean进行操作的四种方式

public class Descriptor {

        public static void main(String[] args) throws Exception {

               // 方式1

               PropertyDescriptor descriptor = new PropertyDescriptor("x", TestDemo1.class);

               Method readMethod = descriptor.getReadMethod();

               TestDemo1 testDemo1 = new TestDemo1();

               Object invoke = readMethod.invoke(testDemo1);

               if (invoke instanceof String) {

                       System.out.println((String) invoke);

               }

               // 方式2 这个方法只能得到所有的方法

               BeanInfo beanInfo = Introspector.getBeanInfo(TestDemo1.class);

               PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();

               for (PropertyDescriptor propertyDescriptor : descriptors) {

                       if (propertyDescriptor.getName().equals("x")) {

                               System.out.println(propertyDescriptor.getName());

                       }

               }

               // 方式3

               Class testClass = TestDemo1.class;

               Object newInstance = testClass.newInstance();

               if (newInstance instanceof TestDemo1) {

                       System.out.println(((TestDemo1) newInstance).getX());

               }

               // 方式4

               Class testClass1 = Class.forName("cn.reflect.collection.TestDemo1");

               Field declaredField = testClass1.getDeclaredField("x");

               if (!declaredField.isAccessible()) {

    //类似与上判断是否是公有的属性

    // if(!Modifier.isPublic(declaredField.getModifiers())){

                       declaredField.setAccessible(true);

               }

                System.out.println(declaredField.get(testDemo1));

        }

}

class TestDemo1 {
        private String x = "qwe";

        public String getX() {
               return x;
        }

        public void setX(String x) {
               this.x = x;
        }

}

3.利用反射获取注解

//RetentionPolicy  枚举  RetentionPolicy.RUNTIME 运行时起作用,必须使用运行时才能够反射

@Retention(RetentionPolicy.RUNTIME)//元注解

// ElementType 枚举 ElementType.TYPE 修饰于类,接口,枚举,注解

@Target(ElementType.TYPE)

@interface ReflectAnnotationdemo1 {

        // value可以省略 value= ,省略的前提是只有

        String value();

}

@ReflectAnnotationdemo1("111")

class AnnotationDemo1 {

}

 public class AnnotationDemo {

        public static void main(String[] args) {

               AnnotationDemo1 annotationDemo1 = new AnnotationDemo1();

               Class<? extends AnnotationDemo1> class1 = annotationDemo1.getClass();

               if (class1.isAnnotationPresent(ReflectAnnotationdemo1.class)) {

                       ReflectAnnotationdemo1 annotation = class1.getAnnotation(ReflectAnnotationdemo1.class);

                       System.out.println(annotation.value());

               }

        }

}

4.对泛型的反射

public class ReflectGenericity {
	private static final String ParameterizedType = null;

	public static void main(String[] args) throws NoSuchMethodException, SecurityException {
		//获取父类的参数化类型
		Type genericSuperclass = ReflectGenericityTest1.class.getGenericSuperclass();
		if (genericSuperclass instanceof ParameterizedType) {
			Type[] actualTypeArguments = ((ParameterizedType) genericSuperclass).getActualTypeArguments();
			System.out.println(actualTypeArguments[0]);
		}
		//获取类型
		Method[] methods = ReflectGenericityTest.class.getMethods();
		for (int i = 0; i < methods.length; i++) {
			if(methods[i].getName().equals("test1")){
				Parameter[] parameters = methods[i].getParameters();
				System.out.println(parameters[0]);
				break;
			}
		}
		//获取参数化类型
		Method method = ReflectGenericityTest.class.getMethod("test2", Vector.class);
		Type[] genericParameterTypes = method.getGenericParameterTypes();
		System.out.println(genericParameterTypes[0]);
	}
}

class ReflectGenericityTest<T> {
	public static <E> E test1(E e) {
		return e;
	}
	public static void test2(Vector<String> e) {
	}
}

class ReflectGenericityTest1<T> extends ReflectGenericityTest<T> {
}

 5.反射的工具类

public class ReflectUtils {
	public static Class getSuperClass(Class clazz, int index) {
		Type gentype = clazz.getGenericSuperclass();
		if (!(gentype instanceof ParameterizedType)) {
			return Object.class;
		}
		Type[] params = ((ParameterizedType) gentype).getActualTypeArguments();
		if (index >= params.length || index < 0) {
			return Object.class;
		}
		if (!(params[index] instanceof Class)) {
			return Object.class;
		}
		return (Class) params[index];
	}

	public static <T> Class<T> getSupergType(Class clazz) {
		return getSuperClass(clazz, 0);
	}

	public static Method getDecaredMethod(Object obj, String methoname, Class<?>[] paraterty) {
		for (Class clazz = obj.getClass(); clazz != Object.class; clazz.getSuperclass()) {
			try {
				return clazz.getDeclaredMethod(methoname, paraterty);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void makeAccsible(Field field) {
		// getmodifys获取各种权限的叠加整型
		if (Modifier.isPublic(field.getModifiers())) {
			field.setAccessible(true);
		}
	}

	public static Field getDecaredMethod(Object obj, String fieldname) {
		for (Class clazz = obj.getClass(); clazz != Object.class; clazz.getSuperclass()) {
			try {
				return clazz.getDeclaredField(fieldname);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// ArrayList<Object> arrayList = new ArrayList<String>();
		return null;
	}

	public static Object invokeMethod(Object obj, String methoname, Class<?>[] paraterty, Object[] parame) {
		Method method = getDecaredMethod(obj, methoname, paraterty);
		if (method == null) {
			throw new IllegalAccessError();
		}
		if (Modifier.isPublic(method.getModifiers())) {
			method.setAccessible(true);
		}
		try {
			method.invoke(obj, parame);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void setFieldValue(Object obj, String fieldname, Object param) {
		Field field = getDecaredMethod(obj, fieldname);
		if (field == null) {
			throw new IllegalAccessError();
		}
		makeAccsible(field);
		try {
			field.set(obj, param);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
	}

	public static Object geyFieldValue(Object object, String name) {
		Field field = getDecaredMethod(object, name);
		if (field == null) {
			throw new IllegalArgumentException("not find field!");
		}
		try {
			field.get(object);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}
}

 

java的反射基础入门

标签:getbean   cto   oid   intro   retention   name   param   tar   array   

原文地址:https://www.cnblogs.com/gg128/p/9311210.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!