我已经在Java中使用过Reflection.但是,如果您使用的是Java标准(例如,注入私有字段),则必须编写大量代码才能完成工作.
在Java对象中注入私有字段的最短方法是什么?广泛使用且可用于生产环境的库中是否有实现?
解决方案一线"
FieldUtils.writeField(对象目标,字符串fieldName,对象值,布尔值ForceAccess)如果您的项目使用 Apache Commons Lang 通过反射设置值的最短方法是在类'org.apachemons.lang3.reflect.FieldUtils' 中使用静态方法'writeField'>
下面的简单示例显示了带有字段PaymentService的Bookstore-Object.该代码显示了如何使用不同的值两次设置私有字段.
import org.apachemons.lang3.reflect.FieldUtils;公共类Main2 {公共静态void main(String [] args)抛出IllegalAccessException {书店书店= new Bookstore();//只需一行就可以通过反射注入场FieldUtils.writeField(bookstore,"paymentService",new Paypal(),true);bookstore.pay();//印刷品:付款人:Paypal//只需一行就可以通过反射注入场FieldUtils.writeField(bookstore,"paymentService",new Visa(),true);bookstore.pay();//支付方式:Visa}公共静态类Paypal实现了PaymentService {}公共静态类Visa实现了PaymentService {}公共静态类书店{私人PaymentService PaymentService;无效的公共薪酬(){System.out.println(付款人:" + this.paymentService.getClass().getSimpleName());}}}您可以通过Maven Central获得lib:
< dependency>< groupId> org.apachemons</groupId>< artifactId> commons-lang3</artifactId>< version> 3.8.1</version></dependency>Hi I've already worked with Reflection in Java. But if you are using the java standards (e.g. injecting a private field) you have to write a lot of code to get the job done.
What is the shortest way to inject a private field in a Java Object? Are there implementations in widely used and production ready libraries?
解决方案The "One-Liner"
FieldUtils.writeField(Object target, String fieldName, Object value, boolean forceAccess)If your Project uses Apache Commons Lang the shortest way to set a value via reflection is to use the static Method 'writeField' in the class 'org.apachemons.lang3.reflect.FieldUtils'
The following simple example shows a Bookstore-Object with a field paymentService. The code shows how the private field is set two times with a different value.
import org.apachemons.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()); } } }You can get the lib via maven central:
<dependency> <groupId>org.apachemons</groupId> <artifactId>commons-lang3</artifactId> <version>3.8.1</version> </dependency>
更多推荐
在Java中通过Reflection设置私有字段的最短,最佳,最干净的方法是什么?
发布评论