How to use annotations in Java to achieve variable parameter passing?

In Java, one way to implement variable parameter passing using annotations is by customizing annotations and using reflection. Below is an example code:

  1. Start by defining a custom annotation to mark the parameters that need to be passed.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Param {
}
  1. Then use this annotation in the classes where parameters need to be passed, marking the variables that need to be passed.
public class Test {
    @Param
    private String param1;

    @Param
    private int param2;

    // getter和setter方法省略
}
  1. Finally, create a utility class that uses reflection to retrieve variables that are marked with annotations and perform parameter passing.
import java.lang.reflect.Field;

public class ParamUtil {
    public static void setParams(Object obj, String param1, int param2) throws IllegalAccessException {
        Class<?> clazz = obj.getClass();
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.isAnnotationPresent(Param.class)) {
                field.setAccessible(true);
                if (field.getType() == String.class) {
                    field.set(obj, param1);
                } else if (field.getType() == int.class) {
                    field.set(obj, param2);
                }
            }
        }
    }
}
  1. Invoke the method of the utility class in the main program to pass parameters.
public class Main {
    public static void main(String[] args) throws IllegalAccessException {
        Test test = new Test();

        ParamUtil.setParams(test, "hello", 123);

        System.out.println(test.getParam1());
        System.out.println(test.getParam2());
    }
}

By following the above steps, it is possible to achieve variable parameter passing functionality using annotations.

Leave a Reply 0

Your email address will not be published. Required fields are marked *