java反射机制常用方法

java反射机制常用方法

反射常用方法

代码片.

package DAO;

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 entity.User;
import 注解.Table;

public class 反射 {

	public static void main(String[] args) 
		//异常
			throws 
			IllegalAccessException, 
			IllegalArgumentException, 
			InvocationTargetException, 
			NoSuchMethodException, 
			SecurityException, 
			ClassNotFoundException, 
			InstantiationException {

/*		
 		反射中getMethods 与 getDeclaredMethods 的区别
		public Method[] getMethods():返回类的所有公用方法:继承类的公用方法和实现接口的方法。
		public Method[] getDeclaredMethods():返回类的的:公共、保护、默认和私有方法、实现接口的方法,但不包括继承的方法。
*/
		
		User user = new User(0, "小明", "123");//创建对象并实例化
		
		//获取类对象
		{
			//获得user类对象,是属于user的类对象
			Class<? extends User> c=user.getClass();
			Class<?> c2=Class.forName("entity.User");
			Class<?> c3=User.class;
		}
		
		
		//获取类成员
		{
			Class<?> c=null;//类对象
			//获得类对象,c上所以注解对象
			Annotation[] annotations = c.getAnnotations();
			Annotation[] annotations1 = c.getDeclaredAnnotations();
			
			//获得类对象,c上的所以字段对象
			Field[] fields=c.getFields();
			Field[] fields1=c.getDeclaredFields();
			
			//获得类对象,c上的所以构造方法对象
			Constructor<?>[] constructors = c.getConstructors();
			Constructor<?>[] constructors1 = c.getDeclaredConstructors();
			
			//获得类对象,c上的所以(非构造)方法对象
			Method[] methods=c.getMethods();
			Method[] methods1=c.getDeclaredMethods();
			
			//获得类对象,c上@Table注解的实例
			Table table=(Table) c.getAnnotation(Table.class);
			String methodName = null;//方法名
			//获得类对象,c上methodName方法对象
			Method method=c.getMethod(methodName);
//	      Method method=c.getMethod(方法名,参数类型.class,参数类型...);
		}
		
		//执行方法
		{
			Constructor constructors=null;//构造函数对象
			//用构造函数创建新对象
			User user2=(User)constructors.newInstance(1,"小明","123");
			
			Method method=null;//方法对象
			//执行方法,获得结果
			Object fieldValue=method.invoke(user);
//			Object fieldValue=method.invoke(对象,参数值);
				
		}
		
		Class<?> c=null;//类对象
		//判断c上是否有注解@Table
		boolean b=c.isAnnotationPresent(Table.class);
		
		Field field = null;	//字段对象
		//获得字段名
		String fieldName=field.getName();
			
					
	}
	
}

说明
反射中getMethods 与 getDeclaredMethods 的区别:

  1. public Method[] getMethods():返回类的所有公用方法:继承类的公用方法和实现接口的方法。
  2. public Method[] getDeclaredMethods():返回类的的:公共、保护、默认和私有方法、实现接口的方法,但不包括继承的方法。

总结

	1. 反射可以在对象运行时操作对象,提高了灵活性。 
**引用包是最大的困难(一步一步来)**
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值