gpt4 book ai didi

java - 您可以使用 OGNL 访问私有(private)变量吗?

转载 作者:行者123 更新时间:2023-11-30 11:00:53 26 4
gpt4 key购买 nike

有没有使用 OGNL访问未作为 bean 属性公开的私有(private)变量(即没有 get/set 方法对)?我想将 OGNL 用作单元测试中使用的更快、更清晰的反射方法。

这是我的代码:

@Test
public void shouldSetup() throws OgnlException{
class A{
private Object b = "foo";
private Object c = "bar";
public Object getB(){ return b; }
}
A a = new A();

System.out.println( "This'll work..." );
Ognl.getValue( "b", a );

System.out.println( "...and this'll fail..." );
Ognl.getValue( "c", a );

System.out.println( "...and we'll never get here." );
}

最佳答案

其实你可以。您需要在 OgnlContext 中设置 MemberAccess 以允许访问非公共(public)字段,并使用 getValue(ExpressionAccessor expression, OgnlContext context, Object root) 方法来检索值。

@Test
public void shouldSetup() throws OgnlException {
class A {
private Object b = "foo";
private Object c = "bar";
public Object getB() { return b; }
}
A a = new A();

// set DefaultMemberAccess with allowed access into the context
OgnlContext context = new OgnlContext();
context.setMemberAccess(new DefaultMemberAccess(true));

System.out.println( "This'll work..." );
// use context in getValue method
Ognl.getValue( "b", context, a );

System.out.println( "...and this'll work..." );
// use context in getValue method
Ognl.getValue( "c", context, a );

System.out.println( "...and we'll get here." );
}

关于java - 您可以使用 OGNL 访问私有(private)变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31388875/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com