Java-反射

实例

示例一

ReflectDemo.java

  • 创建一个properties文件,把他加载进入类。
package com.gl.reflect;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Properties;
public class ReflectDemo {
   public static void main(String[] args) throws IOException, NoSuchMethodException, ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
       //创建Properties对象,用Properties对象调用load方法把要加载的文件流传进去
       Properties pro=new Properties();
      // 获取当前类的字节码文件
       Class reflectDemoClass = ReflectDemo.class;
       //用当前类的Class对象调用getClassLoader()方法可以得到类加载器,类加载器的getResourceAsStream方法把要加载的文件路径传进去得到输入流作为load的参数
       InputStream resourceAsStream = reflectDemoClass.getClassLoader().getResourceAsStream("pro.properties");
        if(resourceAsStream==null) System.out.println("文件找不到");
       System.out.println(System.getProperty("user.dir"));
       //加载配置文件
       pro.load(resourceAsStream);
       //获得配置文件的value
       String methodName = pro.getProperty("methodName");
       String source2 = pro.getProperty("source");
       //获得Person类的Class对象
       Class<?> source1 = Class.forName(source2);
       //用Person类的Class对象创建Person对象
       Object o = source1.newInstance();
       //获得Person对象
       Method method = source1.getMethod(methodName);
       method.invoke(o);
    }
}

示例二

Reflect.java

package com.gl.annotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@Pro(className = "com.gl.domain.Person",methodName = "eat")
public class Reflect {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, ClassNotFoundException {
        //获得该类的字节码文件对象
        Class reflectClass = Reflect.class;
        //Annotation annotation = reflectClass.getAnnotation(Pro.class);
        /*Pro annotation1 = annotation.annotationType().getAnnotation(Pro.class);
        System.out.println(annotation1.className());
        System.out.println(annotation1.methodName());*/
        //获得上面的注解定义位置的对象
        Pro pro = (Pro) reflectClass.getAnnotation(Pro.class);
        //调用注解中的抽象方法方法,实际是创建了接口实现类的对象,该实现类重写了注解接口里面的方法
        String s = pro.methodName();
        System.out.println(s);
        String s1 = pro.className();
        System.out.println(s1);

        //获得实体类的字节码文件对象
        Class<?> aClass1 = Class.forName(s1);
        //用该字节码文件对象创建对象
        Object o = aClass1.newInstance();
        //用该字节码文件获得里面的方法
        Method eat = aClass1.getMethod(s);
        //执行方法
        eat.invoke(o);


    }
}


    }
}

Pro.java

package com.gl.annotation;

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

@Target(value = ElementType.TYPE)
@Retention(value = RetentionPolicy.RUNTIME)
public @interface Pro {
    String methodName();
    String className();
}

示例三

Calculator.java

package com.gl.reflect;

public class Calculator {
   @Check()
    public  void add(){
       System.out.println(100/0);
       System.out.println("1+1="+1+1);
    }
    @Check()
    public void sub(){
        System.out.println("1-1="+(1+1));
    }
    @Check
    public void multiply(){
        System.out.println("1*1="+1*1);
    }
    @Check
    public void chu(){
        System.out.println("1/1="+(1/0));
    }
    public void check(){
        System.out.println("代码完美,没有bug");
    }

}

Check.java

package com.gl.reflect;

public class Calculator {
   @Check()
    public  void add(){
       System.out.println(100/0);
       System.out.println("1+1="+1+1);
    }
    @Check()
    public void sub(){
        System.out.println("1-1="+(1+1));
    }
    @Check
    public void multiply(){
        System.out.println("1*1="+1*1);
    }
    @Check
    public void chu(){
        System.out.println("1/1="+(1/0));
    }
    public void check(){
        System.out.println("代码完美,没有bug");
    }

}

Demo.java

package com.gl.reflect;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Demo {
    public static void main(String[] args) throws IOException {
        Calculator calculator = new Calculator();
//        Class<Calculator> calculatorClass = Calculator.class;
        Class aClass1 = calculator.getClass();
        Method[] methods = aClass1.getMethods();
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("b.txt"));
        //FileWriter fileWriter = new FileWriter("c.txt");

        int num = 0;

        for (Method method : methods) {
            if (method.isAnnotationPresent(Check.class)) {
                try {
                    method.invoke(calculator);
                } catch (Exception e) {
                    num++;
                    bufferedWriter.write(method.getName() + "发生了异常");
                    bufferedWriter.newLine();
                    //bufferedWriter.write(e.getCause().getClass().getSimpleName());
                    bufferedWriter.write("异常的原因是" + e.getCause().getMessage());
                    bufferedWriter.newLine();

                }

            }
        }
        bufferedWriter.write("发生了" + num + "次异常");
        bufferedWriter.flush();
        bufferedWriter.close();

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

麻烦放收发室,谢谢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值