【代码积累】reflection study

import java.lang.reflect.*;
import java.util.Map;


public class Test {
	public String name = null;
	private int cnt = 1;
	
	public void setCnt(int cnt)
	{
		this.cnt = cnt;
	}
	
	public Test()
	{
		
	}
	
	public Test(String name)
	{
		this.name = name;
	}
	
	public void test()
	{
		Method[] method = Test.class.getMethods();
		for( Method item:method )
		{
			System.out.println("Method in test: "+item.getName());
		}
		
		/*Get fields*/
		Field[] fields = Test.class.getFields();
		for( Field field:fields )
		{
			System.out.println("field name ="+field.getName()); /*Only private fields can be accessed*/
		}
		
		/*Modify field value*/
		try
		{
			Field namefield = Test.class.getField("name");
			
			Test newtest = new Test();
			newtest.name = new String("hahaha");
			
			String value = (String)namefield.get(newtest); /*Use the Field object to get value of this field belongs to the specific object*/
			System.out.println("value ="+value);
			
			/*Now modify the field*/
			value = new String("heiheihei");
			namefield.set(newtest, value);
			System.out.println("new value="+newtest.name);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		/*Get all constructors*/
		Constructor<?>[] constructors = Test.class.getConstructors();
		for( Constructor cons:constructors )
		{
			System.out.println("Constructor name="+cons.getName());
		}
		
		/*Get the constructor that takes a String as argument*/
		try
		{
			/*usr constructor to instantiate an object*/
			Constructor cons = Test.class.getConstructor(String.class);
			
			Test test1 = (Test)cons.newInstance("CreatedViaConstructorClass");
			System.out.println("Name = "+test1.name);
		
			/*Get class name*/	
			System.out.println("modifiers: "+ Test.class.getModifiers());
			System.out.println("name: "+Map.class.getName());
			System.out.println("simple-name: "+Map.class.getSimpleName());
			System.out.println("");
			
			/*Get method,use the method object to invoke the method*/
			Method methodlocal = Test.class.getMethod("test", null);
			Test test2 = new Test();
			System.out.println("++++++++++\r\n");
			//Object returnvalue = methodlocal.invoke(test2, null);
		
			
			/*@Get privite field*/
			Field fieldint = Test.class.getDeclaredField("cnt"); /*getField can only get public fields*/
			fieldint.setAccessible(true);
			
			Test test3 = new Test();
			test3.setCnt(12);
			
			int cntvalue = fieldint.getInt(test3);
			System.out.println("private field cnt ="+cntvalue);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public String classname()
	{
		return Test.class.getSimpleName();
	}
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值