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

1、自定义注解



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

2、执行注解类

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

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.reflections.Reflections;
import org.springframework.stereotype.Service;


public class GateWay {
	 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("a");//自定义注解的WayCode值,调用不同的方法
	        requestInfo.setWayName("测试类1");
	        requestInfo.setMap(map);
	 
	        GateWay gate = new GateWay();
	        ResponseInfo responseInfo = gate.gateWay(requestInfo);
	    }
	 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())) {
	                        try {
	                            //执行method
	                            responseInfo = (ResponseInfo) method.invoke(clazz.newInstance(), requestInfo.getMap());
	                        } catch (Exception e) {
	                            e.printStackTrace();
	                        }
	                    }
	 
	                }
	          }
	     }
		return responseInfo;
	 }
}
	 

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

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

import java.util.Map;

import org.springframework.stereotype.Service;

@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、以下是实体类

RequestInfo

import java.util.Map;

public class RequestInfo {
	private String WayCode;
	private String WayName;
	private  Map<String, Object> map;
	public String getWayCode() {
		return WayCode;
	}
	public void setWayCode(String wayCode) {
		WayCode = wayCode;
	}
	public String getWayName() {
		return WayName;
	}
	public void setWayName(String wayName) {
		WayName = wayName;
	}
	public Map<String, Object> getMap() {
		return map;
	}
	public void setMap(Map<String, Object> map) {
		this.map = map;
	}
	
}

ResponseInfo

public class ResponseInfo {
	private String TestId;
	private String TestName;
	public String getTestId() {
		return TestId;
	}
	public void setTestId(String testId) {
		TestId = testId;
	}
	public String getTestName() {
		return TestName;
	}
	public void setTestName(String testName) {
		TestName = testName;
	}
	
}

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>

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要实现不同目标方法执行不同逻辑,可以使用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注解,如果有,则获取注解信息,并根据注解信息执行不同的逻辑。 在这个简单的例子中,我们可以看到使用自定义注解和反射机制可以实现不同目标方法执行不同逻辑的功能。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值