反射基础

package com.a;

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

class Person{
	private String name;
	private int age;
	public  Person(){};
	public Person(String name){
		this.setName(name);
	}
	public Person(String name,int age){
		this(name);
		this.setAge(age);
		
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getName() {
		return name;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public int getAge() {
		return age;
	}
    public void show(){
    	System.out.println(this.name+"   "+this.age);
    }
    
		
	
}

public class Test1 {
	public static void main(String[] args) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, ClassNotFoundException, InstantiationException, NoSuchFieldException{
	Class ps=Person.class;
	System.out.println(ps.getName());
	/*
	 * 使用反射调用构造函数建立对象
	 */
	Constructor mt1=ps.getConstructor(String.class,int.class);//获取构造函数的方法,参数:空不填,其他为类型.class
	System.out.println(mt1);//打印得到的构造函数的方法名
	Person per=(Person) mt1.newInstance("jiengyh",20);//通过得到的构造器的newInstance方法来建立对象,括号中的参数为构造函数的参数。
	per.show();
	
	//通过反射获取并操作方法
	Method mt=ps.getMethod("setName",String.class); //获取指定的公有方法,括号内的参数为,第一个是方法名称,以后为传入参数的数据类型加.class
	mt.invoke(per, "huazehui");
	per.show();
	//通过反射,修改属性值
	Field f=ps.getDeclaredField("name");
	f.setAccessible(true);
	f.set(per, "jiengyh520");
	
	Field f1=ps.getDeclaredField("age");
	f1.setAccessible(true);
	f1.set(per, 25);
	per.show();
	
	
	/*
	 * 把所有的构造函数放在一个Constructor[]数组中并遍历打印
	Constructor[] mt=ps.getConstructors();
	
	for(Constructor c:mt){
		System.out.println(c);
	}
   */
	
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值