JAVA反射基础与应用

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * java反射
 * 成员变量 Field
 * 方法 Method
 *
 */
public class T {
    public static void main(String[] args) throws Exception {
        //成员变量反射
        M m = new M(3,5);
        Field fieldx = M.class.getDeclaredField("x");   //获取对应字段
        fieldx.setAccessible(true); //强制访问 x为private
        System.out.println(fieldx.get(m)); //获取字段对应结果
        Field fieldy = M.class.getDeclaredField("y");   //获取对应字段
        System.out.println(fieldy.get(m)); //获取字段对应结果

        System.out.println("-----------反射成员变量---Field-----------------");
        changer(m);
        System.out.println(m);

        System.out.println("-----------反射方法---Method-----------------");
        String str= "aa";
        System.out.println(str.getClass().getMethods()[1]); //获取所有的方法名称,再通过getMethod获取具体的方法,再通过invoke去调用
        Method method = String.class.getMethod("charAt", int.class);
        System.out.println( method.invoke(str,1));

        System.out.println("----------------用反射调用main方法--------------");
        String className = args[0];
        Method method1 = Class.forName(className).getMethod("main",String[].class);
        method1.invoke(null,new Object[]{new String []{"111","aaa"}});

    }

    //反射修改成员变量的数值
    private static  void changer(Object obj) throws Exception {
        Field[] fields = obj.getClass().getFields();
        for (Field field: fields) {
            //System.out.println(field.getType()); //类型
            //System.out.println(field.get(obj)); //value
            if(field.getType()==String.class){
                 String oldValue = (String)field.get(obj);
                 String newValue = oldValue.replaceAll("a","bbbb");
                 field.set(obj,newValue);
            }
        }
    }
}

class M {
    private int x;
    public  int y;

    public String str1 = "ball";
    public String str2 = "bnb";
    public String str3 = "abd";


    public M(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) {
        for (String a:args
             ) {
            System.out.println(a);

        }
    }

    @Override
    public String toString() {
        return "M{" +
                "x=" + x +
                ", y=" + y +
                ", str1='" + str1 + '\'' +
                ", str2='" + str2 + '\'' +
                ", str3='" + str3 + '\'' +
                '}';
    }
}

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值