java反射分析

         java反射就是提供一种可以在运行时对类进行操作的机制,其作用就是:

  1.      在运行时判断任意对象的所属的类;
  2.      在运行时构造任意类的对象
  3.      在运行时判断任意一个对象具有的成员变量和方法
  4.     在运行时调用任意一个对象的方法
  5.  生成动态代理
       java Reflection API简介:
     在JDK中,实现反射机制的类大都存在于java.lang.reflect中:
     Method:代表类的方法
     Class:代表类本身
     Field:代表类的成员变量(类属性)
     Constructorl类:类的构造方法
     Array类:提供了动态创建数组以及访问数组元素的静态方法
package chapter10;

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

class Reflection{
	private int age;
	public String name;
	public Reflection(){}
	public Reflection(int age,String name){
		this.age=age;
		this.name=name;
	}
	
	private String outName(){
		System.out.println("name:"+name);
		return name;
	}
	public int getAge(){
		return age;
	}
	public void setName(String name){
		this.name=name;
	}
	private void setAge(int age){
		this.age=age;
	}
}
public class TestReflection {
   public static void main(String[] args) throws NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {
	   Reflection r1=new Reflection();
	   Class class1 = r1.getClass();
	   Constructor constructor = class1.getConstructor(int.class,String.class);
	   Object instance = constructor.newInstance(20,"yinjuan");
	   System.out.println(((Reflection)instance).getAge());
	   Method[] methods = Reflection.class.getMethods();
	   for(Method m:methods){
		   System.out.println(m.getName()+"  该方法修饰符为:"+m.getModifiers()+" ,参数个数为:"+m.getParameterCount());
	   }
	   Method[] declaredmethods = Reflection.class.getDeclaredMethods();
	   for(Method m:declaredmethods){
		   System.out.println(m.getName()+"  该方法修饰符为:"+m.getModifiers()+" ,参数个数为:"+m.getParameterCount());
	   }
	   Method m = r1.getClass().getMethod("setName", String.class);
	   m.invoke(instance, "heyiwu");
	   Method m1=r1.getClass().getDeclaredMethod("outName", null);//可以获取私有方法
	   m1.setAccessible(true);
	   m1.invoke(instance, null);
}
      
}

参照:《Java网络编程》

    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值