java通过自定义注解执行指定的类方法

用于三方调用接口的统一入口,入口类GateWay扫描指定包下的service类,遍历该类中带自定义注解的方法,通过不同参数执行指定的方法。

1、自定义注解

@Target({ElementType.FIELD, ElementType.METHOD}) //声明自定义的注解使用在方法上
@Retention(RetentionPolicy.RUNTIME)//注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
@Documented
public @interface MyAnnontation {
    String WayCode() default "none";

    String WayName() default "空";
}

2、执行注解类

使用Reflections扫描包,所有带注解的类都写在com.holly.gateway.service包下。祥见代码

public class GateWay {

    private static final Logger logger = LoggerFactory.getLogger(GateWay.class);

    public ResponseInfo gateWay(RequestInfo requestInfo) {
        ResponseInfo responseInfo = new ResponseInfo();
        Reflections reflections = new Reflections("com.holly.gateway.service");//包名且不可忘记,不然扫描全部项目包,包括引用的jar
        //获取带Service注解的类
        Set<Class<?>> typesAnnotatedWith = reflections.getTypesAnnotatedWith(Service.class);
        for (Class clazz : typesAnnotatedWith
        ) {
            Method[] methods = clazz.getDeclaredMethods();
            for (Method method : methods
            ) {
                //判断带自定义注解MyAnnontation的method
                if (method.isAnnotationPresent(MyAnnontation.class)) {
                    MyAnnontation annotation = method.getAnnotation(MyAnnontation.class);
                    //根据入参WayCode比较method注解上的WayCode,两者值相同才执行该method
                    if (null != annotation.WayCode() && annotation.WayCode().equals(requestInfo.getWayCode())) {
                        logger.info("WayCode = " + annotation.WayCode());
                        try {
                            //执行method
                            responseInfo = (ResponseInfo) method.invoke(clazz.newInstance(), requestInfo.getMap());
                        } catch (Exception e) {
                            logger.info("--------------执行自定义注解方法异常--------------");
                            e.printStackTrace();
                        }
                    }

                }

            }
        }
        return responseInfo;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap();
        map.put("Key1", "参数1");
        map.put("Key2", "参数2");
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setWayCode("b");//自定义注解的WayCode值,调用不同的方法
        requestInfo.setWayName("调测试方法1");
        requestInfo.setMap(map);

        GateWay gate = new GateWay();
        ResponseInfo responseInfo = gate.gateWay(requestInfo);
        logger.info(responseInfo.toString());
    }
}

 

3、在方法上添加@MyAnnontation注解

在步骤2中main方法WayCode传值"b",则执行的是gateWayTwo方法

@Service
public class TestOne {

    @MyAnnontation(WayCode = "a",WayName = "测试类1")
    public ResponseInfo gateWayOne(Map<String, Object> map) {
        System.out.printf("gateWayOne printf" + map.get("Key1"));
        ResponseInfo res = new ResponseInfo();
        res.setTestId("000000");
        res.setTestName("U get Class gateWayOne");
        return res;
    }

    @MyAnnontation(WayCode = "b",WayName = "测试类2")
    public ResponseInfo gateWayTwo(Map<String, Object> map) {
        System.out.printf("gateWayOne printf" + map.get("Key2"));
        ResponseInfo res = new ResponseInfo();
        res.setTestId("000000");
        res.setTestName("U get Class gateWayTwo");
        return res;
    }

    @MyAnnontation
    public ResponseInfo gateWayThree(Map<String, Object> map) {
        System.out.printf("gateWayThree printf" + map.get("Key3"));
        ResponseInfo res = new ResponseInfo();
        res.setTestId("000000");
        res.setTestName("U get Class gateWayThree");
        return res;
    }

    public ResponseInfo gateWay4(Map<String, Object> map) {
        System.out.printf("gateWayThree printf" + map.get("Key4"));
        ResponseInfo res = new ResponseInfo();
        res.setTestId("000000");
        res.setTestName("U get Class gateWay4");
        return res;
    }
}

4、pom.xml

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.reflections/reflections -->
        <dependency>
            <groupId>org.reflections</groupId>
            <artifactId>reflections</artifactId>
            <version>0.9.11</version>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

 

 

  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要实现不同目标方法执行不同逻辑,可以使用Java自定义注解和反射机制。 首先,自定义注解需要用@Target注解来指定使用范围,例如可以指定方法上使用,即@Target(ElementType.METHOD)。 其次,注解需要用@Retention注解来指定生命周期,例如可以指定在运行时依然存在,即@Retention(RetentionPolicy.RUNTIME)。 然后,在目标方法上加上自定义注解,并通过反射获取注解信息,根据注解信息执行不同逻辑。 下面是一个简单的示例代码: ``` @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnotation { String value(); } public class AnnotationDemo { @MyAnnotation("method1") public void method1() { System.out.println("This is method1"); } @MyAnnotation("method2") public void method2() { System.out.println("This is method2"); } public static void main(String[] args) throws Exception { AnnotationDemo demo = new AnnotationDemo(); Method[] methods = demo.getClass().getDeclaredMethods(); for (Method method : methods) { if (method.isAnnotationPresent(MyAnnotation.class)) { MyAnnotation annotation = method.getAnnotation(MyAnnotation.class); if (annotation.value().equals("method1")) { method.invoke(demo); } else if (annotation.value().equals("method2")) { method.invoke(demo); } } } } } ``` 在上面的示例代码中,定义了一个自定义注解@MyAnnotation,并在AnnotationDemo中的两个方法上分别加上了该注解,并指定了不同的value值。 在main方法中,通过反射获取AnnotationDemo中的所有方法,判断方法上是否加上了@MyAnnotation注解,如果有,则获取注解信息,并根据注解信息执行不同的逻辑。 在这个简单的例子中,我们可以看到使用自定义注解和反射机制可以实现不同目标方法执行不同逻辑的功能。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值