共計 849 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用注解來實現變量參數傳遞。以下是一個簡單的示例:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation {String value() default "";
}
public class MyClass {@MyAnnotation(value = "Hello")
private String message;
public String getMessage() {return message;
}
public static void main(String[] args) {MyClass obj = new MyClass();
Class<?> clazz = obj.getClass();
for (java.lang.reflect.Field field : clazz.getDeclaredFields()) {if (field.isAnnotationPresent(MyAnnotation.class)) {MyAnnotation annotation = field.getAnnotation(MyAnnotation.class);
String value = annotation.value();
try {field.setAccessible(true);
field.set(obj, value);
} catch (IllegalAccessException e) {e.printStackTrace();
}
}
}
System.out.println(obj.getMessage()); // Output: Hello
}
}
在上面的示例中,我們定義了一個自定義注解 MyAnnotation
,并將其應用于類的字段message
上。通過反射,我們可以獲取字段上的注解,并將注解中的值賦給字段。最終輸出的結果為Hello
。
丸趣 TV 網 – 提供最優質的資源集合!
正文完