在Java中,可以使用注解來實現變量參數傳遞的方式是通過自定義注解和反射機制來實現。下面是一個示例代碼:
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 {
}
public class Test {
@Param
private String param1;
@Param
private int param2;
// getter和setter方法省略
}
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);
}
}
}
}
}
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());
}
}
通過以上步驟,可以使用注解實現變量參數傳遞的功能。