标签:style class blog code java http
1 import java.lang.reflect.Field; 2 3 import org.junit.Test; 4 5 //反射字段 6 public class Demo2 { 7 8 // 反射字段:public String name="aaaa" 9 @Test 10 public void test1() throws Exception { 11 12 Person p = new Person(); 13 14 Class clazz = Class.forName("Person"); 15 16 Field f = clazz.getField("name"); 17 18 // 获取字段的值 19 Object obj = f.get(p); 20 // 获取字段的类型 21 Class type = f.getType(); 22 23 if (type.equals(String.class)) { 24 String svalue = (String) obj; 25 System.out.println(svalue); 26 } 27 28 // 设置字段的值 29 f.set(p, "xxxxxxxxxx"); 30 System.out.println(p.name); 31 } 32 33 // 反射字段:private int password="aaaa" 34 @Test 35 public void test2() throws Exception { 36 37 Person p = new Person(); 38 39 Class clazz = Class.forName("Person"); 40 41 Field f = clazz.getDeclaredField("password"); 42 43 f.setAccessible(true); 44 45 System.out.println(f.get(p)); 46 } 47 48 // 反射字段:private static int age =332; 49 @Test 50 public void test3() throws Exception { 51 52 Person p = new Person(); 53 54 Class clazz = Class.forName("Person"); 55 56 Field f = clazz.getDeclaredField("age"); 57 58 f.setAccessible(true); 59 60 System.out.println(f.get(p)); 61 } 62 63 }
1 import java.io.InputStream; 2 import java.util.List; 3 4 5 public class Person { 6 7 public String name="hellowrold"; 8 private int password = 123; 9 private static int age =332; 10 11 public Person(){ 12 System.out.println("person"); 13 } 14 15 public Person(String name){ 16 System.out.println("person :"+name); 17 } 18 19 public Person(String name,int password){ 20 System.out.println("person:"+name+password); 21 } 22 23 private Person(List list){ 24 System.out.println("list"); 25 } 26 27 public void method(){ 28 System.out.println("eai1"); 29 } 30 31 public void method(String name,int password){ 32 System.out.println("method"+name+password); 33 } 34 35 public Class[] method(String name,int[] password){ 36 return new Class[]{String.class}; 37 } 38 39 public void method(InputStream in){ 40 System.out.println(in); 41 } 42 43 public static void method(int num){ 44 System.out.println(num); 45 } 46 47 public static void main(String[] args){ 48 System.out.println("main"); 49 } 50 51 }
标签:style class blog code java http
原文地址:http://www.cnblogs.com/aineko/p/3791764.html