通过Reflection in Java设置私有字段的最短,最好,最干净的方法是什么?

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)

  • 设置值后,应将辅助功能设置回"false". (2认同)
  • @AndreasHauschild 不,如果您使用 Field fNew = obj.getClass().getDeclaredField("field"); 创建一个新的 Field 变量;如果不明确设置可访问为 true,则无法更改它。这意味着更改仅适用于 Field f1 的实例。 (2认同)

And*_*ild 9

"一线"

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)

  • @SamzSakerz我明白你在说什么,但这个论点可以用于被认为是"单行"的99%. (3认同)