java中怎么用注解实现变量参数传递

44次阅读
没有评论

共计 1153 个字符,预计需要花费 3 分钟才能阅读完成。

在 Java 中,可以使用注解来实现变量参数传递的方式是通过自定义注解和反射机制来实现。下面是一个示例代码:

  1. 首先定义一个自定义注解,用于标记需要传递的参数:
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. 然后在需要传递参数的类中使用该注解标记需要传递的变量:
public class Test {@Param
    private String param1;

    @Param
    private int param2;

    // getter 和 setter 方法省略 
}
  1. 最后编写一个工具类,通过反射机制来获取被注解标记的变量,并进行参数传递:
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. 在主程序中调用工具类的方法来传递参数:
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());
    }
}

通过以上步骤,可以使用注解实现变量参数传递的功能。

丸趣 TV 网 – 提供最优质的资源集合!

正文完
 
丸趣
版权声明:本站原创文章,由 丸趣 2024-03-19发表,共计1153字。
转载说明:除特殊说明外本站除技术相关以外文章皆由网络搜集发布,转载请注明出处。
评论(没有评论)