反编译(属性、方法、构造方法)

反编译

反编译Field(属性)

public class ReflectTest06 {
    public static void main(String[] args) throws Exception{
        StringBuilder s = new StringBuilder();
        Class studentName = Class.forName("java.lang.Thread");

        s.append(Modifier.toString(studentName.getModifiers()) + " class " + studentName.getSimpleName()+ "{\n");

        Field[] fields = studentName.getDeclaredFields();
        for (Field field : fields) {
            s.append("\t");
            s.append(Modifier.toString(field.getModifiers()));
            s.append(" ");
            s.append(field.getType());
            s.append(" ");
            s.append(field.getName());
            s.append(";\n");
        }

        s.append("}");
        System.out.println(s);
    }
}

获取Field中的属性并赋值

import java.lang.reflect.Field;

/*
* 虽然采用了反射机制,但三要素还是缺一不可:
*       要素1: 对象
*       要素2: 属性
*       要素3: 值
*
* */
public class ReflectTest07 {
    public static void main(String[] args) throws Exception {

        // 获取整个student Class类
        Class studentClass = Class.forName("番外篇反射机制.bean.Student");
        Object obj = studentClass.newInstance();
        // getDeclaredField("属性的名称") 获取单个属性
        Field noField = studentClass.getDeclaredField("no");

        // 给obj对象的no属性赋值
        noField.set(obj, 12323);
        // 读取属性的值
        System.out.println(noField.get(obj));

        Field nameField = studentClass.getDeclaredField("name");

        // 打破封装:
        // 这样设置之后,在外部也可以调用private的
        nameField.setAccessible(true);

        nameField.set(obj,"xiaoluo");
        System.out.println(nameField.get(obj));
    }
}

反编译Method(方法)

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

/*
* 反编译的类中的Method方法
*     public boolean login(String name,String password){

 *       1.Modifier.toString(userService.getModifiers()):pubilc
 *       2.userService.getReturnType():boolean
 *       3.userSerivce.getSimpleName():login
 *       4.Class[] parameterTypes = userService.getParameterTypes();
 *         for(Class parameter:parameters){
 *              s.append(parameter.getSimpleName()):String
 *         }
*
* */
public class ReflectTest09 {
    public static void main(String[] args) throws Exception {
        StringBuilder s = new StringBuilder();
        Class userService = Class.forName("java.lang.String");
        s.append(Modifier.toString(userService.getModifiers()) + " class " + userService.getSimpleName() + "{\n");

        Method[] methods = userService.getDeclaredMethods();
        for (Method method : methods) {
            //public boolean login(String name,String password){
            s.append("\t");
            s.append(Modifier.toString(method.getModifiers()));
            s.append(" ");
            s.append(method.getReturnType());
            s.append(" ");
            s.append(method.getName());
            s.append("(");
            Class[] parameterTypes = method.getParameterTypes();
            for (Class parameterType : parameterTypes) {
                s.append(parameterType.getSimpleName());
                s.append(",");
            }
            // 删除指定下标下的字符
            if(parameterTypes.length>0){
                s.deleteCharAt(s.length() - 1);
            }
            s.append("){}\n");
        }
        s.append("}");
        System.out.println(s);
    }
}

获取Method方法并赋值

import 番外篇反射机制.setvice.User;
import java.lang.reflect.Method;


public class ReflectTest10 {
    public static void main(String[] args) throws Exception{

        /*
         * 要素分析:
         *        要素1 : 对象userService
         *           2 : login方法
         *           3 : 实参列表
         *           4 : 返回值
         * */
        // 普通方法调用方法
        User userService = new User();
        boolean loginSuccess = userService.login("admin","123");
        System.out.println(loginSuccess ?"登录成功":"登录失败");

        // 使用反射机制调用方法
        Class userServiceClass = Class.forName("番外篇反射机制.setvice.User");
        //创建对象
        Object obj = userServiceClass.newInstance();//实例化对象
        // 获取Method
        Method loginMethod = userServiceClass.getDeclaredMethod("login", String.class, String.class);
        // 调用方法
        // invoke() 返回一个Object
        /*
        loginMethod 方法
        obj 对象
        "admin","123" 实参
        retValue 返回值
        */
        Object retValue = loginMethod.invoke(obj,"admin","123");
        // 获取返回值
        System.out.println(retValue);
    }
}

反编译Constructor构造方法

package 番外篇反射机制;

import java.lang.module.ModuleFinder;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

/*
* 反编译一个构造方法
* */
public class ReflectTest11 {
    public static void main(String[] args) throws Exception{

        StringBuilder s = new StringBuilder();
        Class userClass = Class.forName("番外篇反射机制.setvice.User");
        s.append(Modifier.toString(userClass.getModifiers()));
        s.append(" class ");
        s.append(userClass.getSimpleName());
        s.append("{\n");

        // 拼接构造方法
        Constructor[] constructors = userClass.getDeclaredConstructors();
        for (Constructor constructor : constructors) {
            //    public User(int no, String name, String birth, boolean sex) {
            s.append("\t");
            s.append(Modifier.toString(userClass.getModifiers()));
            s.append(" ");
            s.append(userClass.getSimpleName());
            s.append("(");
            // 拼接参数
            Class[] parameterTypes = constructor.getParameterTypes();// 获取参数
            for (Class parameterType : parameterTypes) {
                s.append(parameterType.getSimpleName());
                s.append(",");
            }
            // 删除指定数组的下标
            if (parameterTypes.length>0){
                s.deleteCharAt(s.length() - 1);
            }
            s.append("){}\n");
        }
        s.append("}");
        System.out.println(s);
    }
}

获取构造方法并赋值

package 番外篇反射机制;

import 番外篇反射机制.setvice.User;
import java.lang.reflect.Constructor;

/*
无论是有参还是无参都要进行newInstance()实例化
* */
public class ReflectTest12 {
    public static void main(String[] args) throws Exception{

        // 不使用反射机制获取构造方法
        User user = new User();

        // 使用反射机制获取对应的类
        Class  c = Class.forName("番外篇反射机制.setvice.User");

        // 调用无参构造方法
        Object obj = c.newInstance();
        System.out.println(obj);

        // 获取对应的构造方法
        Constructor con = c.getDeclaredConstructor(int.class);
        //调用有参构造
        // IllegalArgumentException :非法数据异常
        Object newobj = con.newInstance(11);
        System.out.println(newobj);
    }
}

通过反射机制获取注解中的属性

package Annotation.Test03;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

// 只允许该注解可以标注类和方法
@Target({ElementType.TYPE,ElementType.METHOD})
// 希望这个注解可以被fans
@Retention(RetentionPolicy.RUNTIME)//必须是RUNTIME才能被反射机制获取得到class文件
public @interface MyAnnotation {
    String value() default "dff";
}

package Annotation.Test03;

@MyAnnotation("www")
public class MyAnnotationTest {
    int i;
}


package Annotation.Test03;
//该方法是为了获取位于类上的注解属性
public class ReflectAnnotationTest {
    public static void main(String[] args) throws Exception{

        Class c = Class.forName("Annotation.Test03.MyAnnotationTest");
        // 判断类上是否有@MyAnnotation
        //System.out.println(c.isAnnotationPresent(MyAnnotation.class));
        if (c.isAnnotationPresent(MyAnnotation.class)){
            // 获取注解对象
            MyAnnotation myAnnotation = (MyAnnotation) c.getAnnotation(MyAnnotation.class);
            System.out.println("类上面的注解对象" + myAnnotation);

            // 获取注解对象中的属性
            String value = myAnnotation.value();
            System.out.println(value);
        }
        System.out.println();
    }
}

package Annotation.Test04;

import java.lang.reflect.Method;
// 该方法是为了获取doSome方法上的注解的
public class ReflectAnnotationTest {
    @MyAnnotation(zhanghao = "zhangsan",password = "123")
    public void doSome(){

    }

    public static void main(String[] args) throws Exception{
        Class c = Class.forName("Annotation.Test04.ReflectAnnotationTest");
        // 获取doSome方法
        Method deSomeMethod = c.getDeclaredMethod("doSome");
        if (deSomeMethod.isAnnotationPresent(MyAnnotation.class)){
            MyAnnotation myAnnotation = deSomeMethod.getAnnotation(MyAnnotation.class);
            System.out.println(myAnnotation.zhanghao());
            System.out.println(myAnnotation.password());
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值