java 反射笔记

public class Book {
	
	private String name;
	public String type;
	
	public Book(){
		
		
	}
	
	public Book(String name,String type){
		
		this.name = name;
		this.type = type;
		
	}

	public String getName() {
		System.out.println("通过反射,你调用了我的方法,得到了我的名字");
		return name;
	}

	public void setName(String name) {
		this.name = name;
		System.out.println(this.name);
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}
	
	public void showMoreType(String one,String two){
		System.out.println("------------"+ one + "---------------"+ two);
	}
}


public class MethodMain {
	
	public static void main(String[] args) {
		Book book = new Book();
		book.setType("书本");
		showMothod(book);
	}

	public static void showMothod(Object obj){
		try {
			
			Class cl = obj.getClass();//获得对象的类型
			
			Field[] fields = cl.getDeclaredFields();//访问所有属性对象(公有和私有)
			for (Field field : fields) {
				System.out.println(field.getName());
			}
			
			Field[] f = cl.getFields();//只能访问公共属性对象
			for (Field field : f) {
				field.setAccessible(true);//要获得私有属性的值需要家该语句
				System.out.println("属性名:" + field.getName() + "值:" + field.get(obj));//field.get(obj)获取属性值
				System.out.println(field.getModifiers());//属性的权限修饰符
				System.out.println(field.getType());//方法类型
			}
			
			
			Method method = cl.getMethod("getName", null);//获得方法名对象类型,参数为空,所以null
			method.invoke(obj, new Object[0]);//对象,参数为空
			
			Method m = cl.getMethod("setName", String.class);//获得setName的方法类型,参数为String类型
			m.invoke(obj, "name");//对象,参数为“name”
			
			//多参数 方法
			Method method2 = cl.getMethod("showMoreType", new Class[]{String.class,String.class});
			method2.invoke(obj, new Object[]{"肖","斌"});
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
 




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值