JavaSE基础-------反射

1 篇文章 0 订阅

实体类Role

package com.oplb.test;

public class Role {
	Role(){
		
	}
	private Role(int age,String name){
		this.age=age;
		this.name=name;
	}
	private int age;
	private String name;
	public int getAge() {
		return age;
	}
	private void setAge(int age) {
		this.age = age;
	}
	private String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Role[age "+age+",name "+name+"]";
	}
	
}

封装工具类RectUtils

package com.oplb.test;

import java.lang.reflect.Field;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public class RectUtils {
	public static Class getSuperClassGenericType(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];
		
	}
	/**
	 * 通过反射获取class定义中的父类的参数类型
	 * @param clazz
	 * @return
	 */
	public static <T> Class<T> getSuperGenericType(Class clazz){
		
		
		
		return getSuperClassGenericType(clazz, 0);
		
	}
	
	/**
	 * 
	 * @param object
	 * @param methodName
	 * @param parameterTypes
	 * @return
	 */
	public static Method getDeclaredMethod(Object object,String methodName,Class<?>[] parameterTypes){
		for(Class<?> superclass=object.getClass();superclass!=Object.class;superclass=superclass.getSuperclass()){
			try {
				return superclass.getDeclaredMethod(methodName, parameterTypes);
			} catch (NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}		
		}
		return null;
	}
	
	//忽略访问修饰符
	public static void makeAccessible(Field field){
		if(Modifier.isPublic(field.getModifiers())){
			field.setAccessible(true);
		}
	}
	public static Field getDeclaredField(Object object, String fieldName){
		
		for(Class<?> superclass = object.getClass();
				superclass!= Object.class;
				superclass = superclass.getSuperclass()){
			
			try {
				return superclass.getDeclaredField(fieldName);
			} catch (SecurityException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (NoSuchFieldException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		return null;
		
	}
	
	//方法的调用
	public static Object invokeMethod(Object object,String methodName,Class<?> [] parmeterTypes,Object...args){
		Method method =getDeclaredMethod(object, methodName, parmeterTypes);
		if(method==null){
			throw new IllegalArgumentException("could not find method  [ "+methodName+" ] on target [ "+object+" ]");
		}
		method.setAccessible(true);
		
		try {
			return method.invoke(object, parmeterTypes);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return null;
		
	}
	public static void setFieldValue(Object object,String fieldName,Object value){
		Field field=getDeclaredField(object, fieldName);
		if(field==null){
			throw new IllegalArgumentException("could not find method  [ "+fieldName+" ] on target [ "+object+" ]");
		}
		makeAccessible(field);
		try {
			field.set(object,value);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public static Object getFieldValue(Object object,String fieldName,Object value){
		Field field=getDeclaredField(object, fieldName);
		if(field==null){
			throw new IllegalArgumentException("could not find method  [ "+fieldName+" ] on target [ "+object+" ]");
		}
		makeAccessible(field);
		Object obj=null;
		try {
			field.get(object);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
	
}

测试类Test

package com.oplb.test;

import java.lang.reflect.Constructor;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Test {
	public static void main(String[] args) {
		try {
			Class clazz=Class.forName("com.oplb.test.Role");
			Constructor<Role> con=clazz.getDeclaredConstructor(null);
			Constructor<Role> con1=clazz.getDeclaredConstructor(new Class[]{int.class,String.class});
			/*Method meth=clazz.getDeclaredMethod("setAge", int.class);
			Field field=clazz.getDeclaredField("age");*/
			con.setAccessible(true);
			con1.setAccessible(true);
			Object obj=con.newInstance(null);
			Object obj1=con1.newInstance(new Object[]{3,"张三"});
			Role rol=(Role) obj;
			Role rol1=(Role) obj1;
			
			/*field=3;*/
			rol.setName("王五");
			System.out.println(rol);
			System.out.println(rol1);
			rol.setName("liuliu");
			Method meth=clazz.getDeclaredMethod("getName", null);
			meth.setAccessible(true);
			Object objresult=meth.invoke(rol, args);
			System.out.println(objresult);
			Method methodSet=clazz.getDeclaredMethod("setAge", new Class[]{int.class});
			methodSet.setAccessible(true);
			Object objset=methodSet.invoke(rol,new Object[]{4});
			System.out.println(objset);
			System.out.println(rol.getAge());
			Field fieldAge=clazz.getDeclaredField("age");
			fieldAge.setAccessible(true);
			fieldAge.set(rol,9);
			System.out.println(fieldAge.get(rol));
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

测试结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值