And*_*ild 6 java reflection java-ee
嗨,我已经使用了Thinking in Java.但是,如果您使用的是java标准(例如,注入私有字段),则必须编写大量代码才能完成工作.
在Java对象中注入私有字段的最短方法是什么?广泛使用和生产就绪库中是否有实现?
Dav*_*INO 12
不使用外部库,您需要:
Field实例如下:
Field f1 = obj.getClass().getDeclaredField("field");
f1.setAccessible(true);
f1.set(obj, "new Value");
Run Code Online (Sandbox Code Playgroud)
"一线"
FieldUtils.writeField(Object target, String fieldName, Object value, boolean forceAccess)
Run Code Online (Sandbox Code Playgroud)
如果您的项目使用Apache Commons Lang ,通过反射设置值的最短方法是使用类'org.apache.commons.lang3.reflect.FieldUtils'中的静态方法'writeField '
以下简单示例显示了具有字段paymentService的Bookstore-Object.该代码显示私有字段如何使用不同的值设置两次.
import org.apache.commons.lang3.reflect.FieldUtils;
public class Main2 {
public static void main(String[] args) throws IllegalAccessException {
Bookstore bookstore = new Bookstore();
//Just one line to inject the field via reflection
FieldUtils.writeField(bookstore, "paymentService",new Paypal(), true);
bookstore.pay(); // Prints: Paying with: Paypal
//Just one line to inject the field via reflection
FieldUtils.writeField(bookstore, "paymentService",new Visa(), true);
bookstore.pay();// Prints Paying with: Visa
}
public static class Paypal implements PaymentService{}
public static class Visa implements PaymentService{}
public static class Bookstore {
private PaymentService paymentService;
public void pay(){
System.out.println("Paying with: "+ this.paymentService.getClass().getSimpleName());
}
}
}
Run Code Online (Sandbox Code Playgroud)
你可以通过maven central获取lib:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
546 次 |
| 最近记录: |