java之反射字段,反射方法

反射字段:

package heng.java.reflect.field;

import java.lang.reflect.Field;

public class ReflectFieldDemo {
	public static void main(String[] args) {
		/*
		 * 获取类中的成员。反射字段。
		 */
		try {
			getFieldDemo();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	public static void getFieldDemo() throws ClassNotFoundException, Exception, Exception{
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);
		//
		//Field field = clazz.getField("age");//该方法只获取公有的。
		Field field = clazz.getDeclaredField("age");
		
		//要对非静态的字段操作必须有对象
		Object obj = clazz.newInstance();
		//使用父类的方法将访问权限检查能力取消。
		field.setAccessible(true);//暴力访问。
		field.set(obj, 40);
		
		System.out.println(field.get(obj));
	}

}


反射方法:

package heng.java.reflect.method;

import java.lang.reflect.Method;

public class ReflectMethodDemo {
	public static void main(String[] args) {
		try {
			getMethodDemo();
			getMethodDemo2();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	//反射方法,静态,无参数的show方法。
	private static void getMethodDemo2() throws Exception {
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);

		Method method = clazz.getMethod("staticShow", null);
		
		method.invoke(null, null);
	}
	//反射方法,非静态,无参数的show方法。
	public static void getMethodDemo() throws Exception {
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);
		
		Method method = clazz.getMethod("show", null);
		Object obj = clazz.newInstance();
		method.invoke(obj, null);
	}
	//反射方法,非静态,无参数的show方法。
	public static void getMethodDemo3() throws Exception{
		String className = "heng.java.reflect.constructor.Person";
		Class clazz = Class.forName(className);
		
		Method method = clazz.getMethod("paramShow", String.class,int.class);
		Object obj = clazz.newInstance();
		
		method.invoke(obj, "wangwu",22);
		
	}

}


 

Person类:

package heng.java.reflect.constructor;

public class Person {
	private String name;
	private int age;
	public Person(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}
	public Person() {
		super();
		System.out.println("Person run");
	}
	
	public void show(){
		System.out.println("person show run");
	}
	public static void staticShow(){
		System.out.println("person static show run");
	}
	public void paramShow(String name, int age){
		System.out.println("show:"+name+"-----"+age);
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值