java反射类的字段:
package com.ma.reflection; import java.lang.reflect.Field; import org.junit.Test; import com.ma.bean.StudentBean; /** * 反射字段 * @author ma * */ public class Demo4 { /** * 反射公有字段 * @throws ClassNotFoundException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException */ @Test public void test1() throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ //加载类 Class<?> clazz = Class.forName("com.ma.bean.StudentBean"); StudentBean s = new StudentBean(); //加载字段 Field field = clazz.getField("name"); //调用字段 String name = (String)field.get(new StudentBean()); //设置字段值 field.set(s, (Object)"关悦"); //输出字段 System.out.println(s.name); System.out.println(name); } /** * 反射私有字段 * @throws ClassNotFoundException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException */ @Test public void test2() throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ //加载类 Class<?> clazz = Class.forName("com.ma.bean.StudentBean"); StudentBean s = new StudentBean(); //加载字段 Field field = clazz.getDeclaredField("work"); field.setAccessible(true); //获取字段 String work = (String)field.get(s); System.out.println(work); } /** * 反射静态字段 * @throws ClassNotFoundException * @throws NoSuchFieldException * @throws SecurityException * @throws IllegalAccessException * @throws IllegalArgumentException */ @Test public void test3() throws ClassNotFoundException, SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException{ ////加载类 Class<?> clazz = Class.forName("com.ma.bean.StudentBean"); StudentBean s = new StudentBean(); //加载字段 Field field = clazz.getDeclaredField("sex"); field.setAccessible(true); //获取字段 String sex = (String)field.get(s); System.out.println(sex); } /** * 反射字段 */ @Test public void test4(){ // // // } /** * 反射字段 */ @Test public void test5(){ // // // } }
实体类Student
package com.ma.bean; /** * 学生类 * @author ma * */ public class StudentBean { public String name = "刘备"; public int age; private String work = "教师"; private static String sex = "男"; public StudentBean() { super(); } public void eat(){ System.out.println("吃饭了。。。。。。。。。。。。。。"); } public void play(String name,int age){ System.out.println(name+":去玩了哟。。。。。。。。。"+age); } public void run(int ...intaa){ System.out.println(":这是可变参数方法"); } private void jump(){ System.out.println("这是私有方法"); } public static void sleep(int age){ System.out.println(age+":这是静态方法"); } public static void main(String[] args) { System.out.println("这是main方法!!!"); } }
原文地址:https://www.cnblogs.com/majingang/p/9116063.html
时间: 2024-10-24 11:27:26