首页 > 代码库 > 反射类的字段
反射类的字段
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 @Test10 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 =http://www.mamicode.com/ (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 @Test35 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 @Test50 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 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。