Java 您可以使用OGNL访问私有变量吗?

Java 您可以使用OGNL访问私有变量吗?,java,reflection,ognl,private-members,Java,Reflection,Ognl,Private Members,是否仍然使用访问未作为bean属性公开的私有变量(即noget/set方法对)?我想使用OGNL作为一种更快、更干净的反射方法,用于单元测试 这是我的密码: @Test public void shouldSetup() throws OgnlException{ class A{ private Object b = "foo"; private Object c = "bar"; public Object getB(){ return

是否仍然使用访问未作为bean属性公开的私有变量(即no
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." );
}

我能做的最好的工作就是直接使用反射:

static Object getValue( final String ognlPath, final Object o ){
    final StringTokenizer st = new StringTokenizer( ognlPath, "." );

    Object currentO = o;
    String nextFieldName = null;
    try{
        while( st.hasMoreTokens() ){
            nextFieldName = st.nextToken();

            if( currentO == null ){
                throw new IllegalStateException( "Cannot find field '" + nextFieldName + "' on null object." );
            }

            Field f = currentO.getClass().getDeclaredField( nextFieldName );
            f.setAccessible( true );
            currentO = f.get( currentO );
        }

        return currentO;

    }catch( NoSuchFieldException e ){
        throw new RuntimeException( "Could not find field '" + nextFieldName + "' on " + currentO.getClass().getCanonicalName(), e );

    }catch( IllegalAccessException e ){
        throw new RuntimeException( "Failed to get from path '" + ognlPath + "' on object: " + o, e );
    }
}

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

@测试
public void shouldSetup()引发OgnlException{
甲级{
私有对象b=“foo”;
私有对象c=“bar”;
公共对象getB(){return b;}
}
A=新的A();
//将DefaultMemberAccess设置为允许访问上下文
OgnlContext context=新的OgnlContext();
setMemberAccess(新的DefaultMemberAccess(true));
System.out.println(“这会有用的…”);
//在getValue方法中使用上下文
Ognl.getValue(“b”,上下文,a);
System.out.println(“…这就行了…”);
//在getValue方法中使用上下文
Ognl.getValue(“c”,上下文,a);
System.out.println(“…我们就到这里了。”);
}