J2EE快速入门之反射

目录

一、什么是反射?

二、如何得到类对象

三、根据类得到类名(全限定名/全路径名)

四、根据类得到类的属性

五、.根据类得到类的方法

六、根据类得到类的构造方法

七、根据类得到类的实现接口列表

八、测试


一、什么是反射?

   反射是一种机制,利用反射机制动态的实例化对象、读写属性、调用方法、构造函数

二、如何得到类对象

   一切反射相关的代码都从获得类对象开始
   3种获取方式:
     1)类名.class;
     2) 对象名.getClass();
     3) Class.forName(全限定名/全路径名)

三、根据类得到类名(全限定名/全路径名)

    1)cName.getName();            -->获取全限定名
    2)cName.getSimpleName();         -->获取类名
    3)cName.getPackage();             -->获取包名

public class HelloTest {

	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {

		// 反射是一种机制,利用反射机制动态的实例化对象、读写属性、调用方法、构造函数。

		// 传统实例化对象与反射机制实例化对的区别
		// 1)传统方式
		Hello hello = new Hello();
		hello.setName("zs");
		System.out.println(hello.getName());

		// 2)反射方式
		// 产生异常:
		// InstantiationException:反射机制实例化异常
		// IllegalAccessException:没有访问权限异常
		// ClassNotFoundException:类没有发现异常
		/*Class cls = Hello.class;
		Object hello1 = cls.newInstance();
		System.out.println(hello1);*/
		
		// 前提:一切与反射相关的操作都从获取类对象开始!!!(3种)
		// ① 类名.class
		Class cls = Hello.class;

		// ② 对象名.getClass()
		Hello h = new Hello();
		Class cls = h.getClass();
		
		// ③ Class.forName(类的全路径名、全限定名)
		Class cls = Class.forName("com.zking.reflect.entity.Hello");
		
		//打印
		System.out.println("全路径名:"+cls.getName());
		System.out.println("简单类名:"+cls.getSimpleName());
		System.out.println("访问修饰符:"+cls.getModifiers());
		System.out.println("类所在包名:"+cls.getPackage());
		

	}

}

四、根据类得到类的属性

    Field field=cla.getField(“属性名”);

    field.getName();                                -->获取属性名            
    filed.getType();                                  -->获取属性类型        
    field.getModifiers();                          -->获取属性访问修饰符    
    field.set(Object,Object);                   -->设置属性值,参数1:要设置属性所在对象;参数2:要设置的值;    
    field.get(Object);                               -->获取属性值,参数:要获取属性值的对象                
    field.getDeclaredField(“属性名”);    -->获取单个属性(私有、公有、受保护、默认、静态)    
    field.getDeclaredFields();                -->获取所有属性(私有、公有、受保护、默认、静态)

五、.根据类得到类的方法

        //无参无返回、无参有参会、有参无返回、有参有返回
    cla.getMethod();                          -->获取单个公有方法
    cla.getDeclaredMethod();           -->获取当个方法(包括私有、受保护、默认、公有)
    cla.getMethods();                        -->获取所有公有方法
    cla.getDeclaredMethods();         -->获取所有的方法(包括私有、受保护、默认、公有)

六、根据类得到类的构造方法

    cla.getConstrutor();                       -->获取单个公有构造方法
    cla.getDeclaredConstrutor();        -->获取单个构造方法(包括私有、受保护、默认、公有)
    cla.getConstrutors();                     -->获取所有的公有构造方法
    cla.getDeclaredConstrutors();      -->获取所有的构造方法(包括私有、受保护、默认、公有)

七、根据类得到类的实现接口列表

Class[] interface=cla.getInterfaces();    -->获取类对象中所有实现接口列表

八、测试

实体类:

package com.lixiangning.reflect.entity;

/**
 * 学生类
 * @author Administrator
 *
 */
public class Student {
	private String sid;

	private String sname;

	public Integer age;
	
	String sex;

	public Student() {
		super();
		System.out.println("调用无参构造方法创建了一个学生对象");
	}

	public Student(String sid) {
		super();
		this.sid = sid;
		System.out.println("调用带一个参数的构造方法创建了一个学生对象");
	}

	public Student(String sid, String sname) {
		super();
		this.sid = sid;
		this.sname = sname;
		System.out.println("调用带二个参数的构造方法创建了一个学生对象");
	}

	@SuppressWarnings("unused")
	private Student(Integer age) {
		System.out.println("调用Student类私有的构造方法创建一个学生对象");
		this.age = age;
	}

	public String getSid() {
		return sid;
	}

	public void setSid(String sid) {
		this.sid = sid;
	}

	public String getSname() {
		return sname;
	}

	public void setSname(String sname) {
		this.sname = sname;
	}

	public void hello() {
		System.out.println("你好!我是" + this.sname);
	}

	public void hello(String name) {
		System.out.println(name + "你好!我是" + this.sname);
	}

	@SuppressWarnings("unused")
	private Integer add(Integer a, Integer b) {
		return new Integer(a.intValue() + b.intValue());
	}
}

测试类:

public class StudentTest {
	
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {
		
		//异常捕捉
		// InstantiationException:反射机制实例化异常
		// IllegalAccessException:没有访问权限异常
		// ClassNotFoundException:类没有发现异常
		// NoSuchFieldException:没有匹配的属性异常
		// NoSuchMethodException:没有匹配的方法异常
		// IllegalArgumentException:元素异常
		
		//获取类对象
		Class cls = Class.forName("com.zking.reflect.entity.Student");
		
		//反射机制实例化对象
		Student stu =(Student) cls.newInstance();
		
		//获取属性(Field)
		//① 获取单个公共的属性
		Field field = cls.getField("age");
		
		//② 获取单个公共的、私有的、受保护的等等属性
		Field field = cls.getDeclaredField("sid");
		
		//③ 获取所有公共的属性
		Field[] fields = cls.getFields();
		
		//④ 获取所有公共的、私有的、受保护的等等属性
    	Field[] fields = cls.getDeclaredFields();
		for (Field field : fields) {
			System.out.println("获取属性名:"+field.getName());
			System.out.println("获取属性访问修饰符:"+field.getModifiers());
			System.out.println("获取属性类型:"+field.getType());
			System.out.println("----------------");
		}
		
		
		//赋值
		Field field = cls.getDeclaredField("sid");
		//设置访问权限
		field.setAccessible(true);
		
		//赋值方法:
		//参数1:实例化对象名
		//参数2:赋值的值
		field.set(stu, "p007");
		
		//取值
		//取值方法:
		//参数:实例化对象名
		Object obj = field.get(stu);
		System.out.println(obj);
		
		//调用方法(Method)
		//方法:有参有返回、有参无返回、无参无返回、无参有返回
		//① 获取单个公共的方法
		Method method = cls.getMethod("hello",null );
		
		//② 获取单个公共的、私有的、受保护的等等方法
		Method method = cls.getDeclaredMethod("hello", String.class);
		
		//③ 获取所有公共的方法
		Method[] methods = cls.getMethods();
		
		//④ 获取所有公共的、私有的、受保护的等等方法
		Method[] methods = cls.getDeclaredMethods();
		
		//打印
		for (Method method : methods) {
			System.out.println("方法名:"+method.getName());
			System.out.println("访问修饰符:"+method.getModifiers());
			System.out.println("方法参数数量:"+method.getParameterCount());
			System.out.println("方法返回类型:"+method.getReturnType());
			System.out.println("----------------");
		}
		
		//调用方法
		Method method = cls.getMethod("hello", String.class);
		Method method = cls.getDeclaredMethod("add", Integer.class,Integer.class);
		//设置访问权限
		method.setAccessible(true);
		//执行方法
		//参数1:实例化对象名
		//参数2:方法参数
		Object returnValue = method.invoke(stu, 20,30);
		System.out.println(returnValue);
			
		//调用构造函数
		Constructor cons = cls.getDeclaredConstructor(Integer.class);
		cons.setAccessible(true);
		cons.newInstance(10);		
	}	
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ning_ning_03

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值