Java的反射机制

1.Java反射机制的网络解析

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

 

2.实际应用

很多时候,我们实例化了一个类之后,想更改它的属性,可程序员很多时候都把一些属性给私有化了,包括一些方法,这个时候,我们就可以使用Java的反射机制去把这个实例里面的属性值进行更改,或者调用这些被私有化的方法

 

3.例子

//先写一个类
public class Father {

	private String name;
	
	public Father(){
		setName("Peter");
	}
	
	private void setName(String name) {
		this.name = name;
	}
	
	public String getName(){
		return name;
	}
}

  

//一个测试类-没有使用反射机制
public class Child {
	public static void main(String[] args) {  
        try{  
            Father father=new Father();  
            System.out.println(father.getName());
            //结果是Peter

        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
          
    }  
}

  

//测试类,使用了反射机制修改变量
public class Child {
	public static void main(String[] args) {  
        try{  
            Father father=new Father();  
            Class<Father> fatherClass=Father.class; 
              
            //访问私有变量  name
            Field field=fatherClass.getDeclaredField("name");
            //设置为修改
            field.setAccessible(true);  
            
            //有两个参数(需要更改变量的实例,变量的值);
            field.set(father, "John");
            System.out.println(father.getName());//输出John 
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
          
    }  
}

  

//调用方法
public class Child {
	public static void main(String[] args) {  
        try{  
            Father father=new Father();  
            Class<Father> fatherClass=Father.class; 
           
            Method method = fatherClass.getDeclaredMethod("setName", String.class);
            method.setAccessible(true);
            method.invoke(father, "Rose");
            System.out.println(father.getName());//输出John 
            
        }catch(Exception ex){  
            ex.printStackTrace();  
        }  
          
    }  
}

这里要注意的是getDeclareMethod()方法与getMethod()方法

getDeclareMethod()获取自身所有的方法,包括public,private,protected

getMethod()获取包括父类的所有public方法

posted @ 2016-02-24 17:19  长命百岁  阅读(166)  评论(0编辑  收藏  举报