Java 反射常用方法示例

<pre name="code" class="java">import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

class Point{
	int x;
	private int y;
	
	public Point(){
		x = 1;
		y = 2;
	}	
	
	public void setX(int x) {
		this.x = x;
	}

	public void setY(int y) {
		this.y = y;
	}

	private Point(int x){
		this();
		this.x = x;
	}
	
	public Point(int x, int y) {
		super();
		this.x = x;
		this.y = y;
	}
	
	public void printPoint(){
		System.out.println("x = " + x + " , y = " + y);
	}
}

public class ReflectTest2 {

	public static void main(String[] args) throws Exception {
		
		//使用第一种方法创建对象
		Class cls1 = Class.forName("Point");
		Constructor con1 = cls1.getConstructor(int.class,int.class);
		Point p1 = (Point) con1.newInstance(5,6);
		p1.printPoint();
		
		//使用第二种方法创建对象
		Class cls2 = Point.class;
		Point p2 = (Point) cls2.newInstance();//无参构造函数
		p2.printPoint();
		
		//使用第三种方法创建对象
		Class cls3 = p1.getClass();
		//使用p1对象的setX方法将x值修改为10
		Method m1 = cls3.getMethod("setX", int.class);
		m1.invoke(p1, 10);
		p1.printPoint();
		
		/*
		 * Note:
		 * getDeclaredConstructor可以返回指定参数的构造函数,
		 * 而getConstructor只能放回指定参数的public的构造函数 
		 * */		
		Constructor con2 = cls3.getDeclaredConstructor(int.class);
		//访问私有变量、函数需要设置accessible
		con2.setAccessible(true);
		Point p4 = (Point) con2.newInstance(3);
		p4.printPoint();
		
		//Field f1 = cls3.getField("y");//error
		Field f1 = cls3.getDeclaredField("y");
		f1.setAccessible(true);
		//获取p1的y值
		System.out.println(f1.get(p1));
	}

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值