本文共 2496 字,大约阅读时间需要 8 分钟。
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(); }}
转载地址:http://nthii.baihongyu.com/