Java 反射 想

所谓反射。是指在执行时状态中,获取类中的属性和方法。以及调用当中的方法的一种机制。

这样的机制的作用在于获取执行时才知道的类(Class)及当中的属性(Field)、方法(Method)以及调用当中的方法,也能够设置当中的属性值。

在Java中实现反射最重要的一步,也是第一步就是获取Class对象,得到Class对象后能够通过该对象调用对应的方法来获取该类中的属性、方法以及调用该类中的方法。
Java中反射有例如以下几种实现方式:
1、通过Class.forName()方法载入字符串,就能够得到该字符串做代表的Class对象。

比如:Class<?

> clazz = Class.forName("java.lang.String")就能够得到String类的Class对象。

值得注意的是,字符串必须是类的全名。即包名+类名。

下边的代码是Struts配置文件struts.xml中的一个action的配置。

 
<action name="registe" class="cn.com.huixin.struts2.RegisteAction">
   <result>/registeResult.jsp</result>
   <result name="input">/registe2.jsp</result>
</action>
 
这里的class属性给出了一个类的全名的字符串,server是怎样通过这个字符串得到类对象的呢?就是通过反射机制RegisteAction对象的。

然后再去调用这个类中的默认的execute()方法。

2、通过类名调用class属性得到该类的Class对象。
比如:Class<?> clazz = String.class也能够得到String类的Class对象。

3、调用实例的getClass()方法。
比如:Date date = new Date();
          Class<?> clazz = date.getClass();
通过上边的两句代码就能够得到date实例的Class对象。


1 获取 反射的对象

package com.qianfeng.reflect;

import com.qianfeng.domain.Person;

/*
反射:动态获取类或类中成员。并使用类或类中成员
获取一个类字节码文件对象的方式 (类名的.class)
*/
public class ReflectDemo1 {

	public ReflectDemo1() {
		// TODO Auto-generated constructor stub
	}
	public static void main(String[] args) throws ClassNotFoundException {
		        
				
				//get1();
				//get2();
		          get3();

	}
	private static void get3() throws ClassNotFoundException {
		//通过字符串形式的名称来获取字节码文件对象,不须要对象。也不须要类
		Class claz = Class.forName("com.qianfeng.domain.Person");
		System.out.println(claz);
		
		
		
	}
	private static void get2() {
		//每一个数据类型都有一个class属性,能够通过类的该属性获取其所属类的字节码文件对象
		//不须要对象。可是须要类
		Class claz = Person.class;
		Class claz2 = Person.class;
		
		System.out.println(claz==claz2);
		
		
	}
	private static void get1() {
		//方式一:通过对象来获取所属类的字节码文件对象
		//不论什么一个对象都有其所属类的字节码文件对象
		//new Person()  Person.class
		//特点:这样的方式须要创建对象

		Person p1 = new Person();

		Class claz1 = p1.getClass();//Person.class

		Person p2 = new Person();

		Class claz2 = p2.getClass();//Person.class

		System.out.println(claz1==claz2);
		
	}

}

2  获取反射的对象的构造方法
package com.qianfeng.reflect;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import com.qianfeng.domain.Person;

public class ReflectDemo2 {

	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 */
	public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
		//动态获取类。并创建对象
        
		createObj();
		
		createObj2();
	}

	private static void createObj2() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//动态获取类
		String str="com.qianfeng.domain.Person";
		Class claz = Class.forName(str);
		//int.class;
		//使用带參数的构造方法创建对象
		//首先要得到带參数的构造方法
		//Person p = new Person("lsdjkf",34);//String.class int.class
		
		Constructor con = claz.getConstructor(String.class,int.class);
		
		//使用获取到的构造方法创建对象
		
		Object obj = con.newInstance("李四",29);//调用构造方法对象的newInstance()方法
		
		System.out.println(obj);
		
		
		
	}

	private static void createObj() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
		//Person p = new Person();
		//1载入Person.class  2:开辟内存  3:构造方法
		
		//动态获取类
		String str="com.qianfeng.domain.Person";
		Class claz = Class.forName(str);
		
		//创建对象
		Object obj = claz.newInstance();//调用这个字节码文件对象的newInstance()方法
		
		System.out.println(obj);
		
	}

}

3 获取对象中的成员变量
package com.qianfeng.reflect;

import java.lang.reflect.Field;



public class ReflectDemo3 {

	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 * @throws SecurityException 
	 * @throws NoSuchFieldException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		// 动态获取类并创建对象后。訪问成员属性
		
		accessField();

	}

	private static void accessField() throws ClassNotFoundException, NoSuchFieldException, SecurityException, InstantiationException, IllegalAccessException {
		//Person p = new Person();
		//p.name = "";
		//动态获取类
		String str="com.qianfeng.domain.Person";
		Class claz = Class.forName(str);
		
		//获取字段
		//Field f = claz.getField("name");//仅仅能获取权限是public的字段
		Field f = claz.getDeclaredField("name");
		//System.out.println(f);
		
		//给字段赋值--须要先有对象
		//创建对象
		Object obj = claz.newInstance();
		
		//设置权限为可訪问的
		
		f.setAccessible(true);//暴力訪问

		//给字段赋值
		
		f.set(obj, "小花");
		
		System.out.println(obj);
		
		
		
	}

}

4 获取对象中的方法
package com.qianfeng.reflect;

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

public class ReflectDemo4 {

	/**
	 * @param args
	 * @throws ClassNotFoundException 
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//动态获取类并创建对象后。訪问成员方法
		
	//	accessMethod();
		accessMethod1();
		accessMethod2();

	}
	
	
	private static void accessMethod2() throws NoSuchMethodException, SecurityException, ClassNotFoundException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
	 	//动态获取类
    	String str="com.qianfeng.domain.Person";
    	Class claz = Class.forName(str);
    	
    	Method m = claz.getMethod("meth", null);
    	
    	m.invoke(null,null);
		
	}


	//得到带參数的方法并运行
    private static void accessMethod1() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    	//动态获取类
    	String str="com.qianfeng.domain.Person";
    	Class claz = Class.forName(str);
    	
    	Method  m = claz.getMethod("func", String.class);
    	
    	Object obj = claz.newInstance();
    	
    	m.invoke(obj, "haha");
    	
		
	}
	//得到不带參数的方法并运行
	private static void accessMethod() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
		//动态获取类
		String str="com.qianfeng.domain.Person";
		Class claz = Class.forName(str);
		
		Method m = claz.getMethod("show",null);
		
		//创建对象
		Object obj = claz.newInstance();
		
		m.invoke(obj,null);
		
		
		
		
	}

}




版权声明:本文博客原创文章,博客,未经同意,不得转载。

posted @ 2015-07-01 17:27  mfrbuaa  阅读(175)  评论(0编辑  收藏  举报