且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用ABAP的RTTI和Java反射机制访问static private属性

更新时间:2022-09-10 09:55:35

In ABAP we can define a static attribute for a class via keyword CLASS-DATA, whose validity is not associated with instances of a class but with the class itself. In order to prove this fact I use the following simple Pointer class for demonstration:

使用ABAP的RTTI和Java反射机制访问static private属性使用ABAP的RTTI和Java反射机制访问static private属性Can we access the static attribute of a class without object instance in debugger?

Since in theory the static attribute belongs to class instead of any dedicated object instance, so question comes: is there approach to monitor the static attribute value in ABAP debugger directly from class instead? Yes it is possible.


(1) type text “{C:ZCL_POINT} in debugger and press enter key

使用ABAP的RTTI和Java反射机制访问static private属性使用ABAP的RTTI和Java反射机制访问static private属性使用ABAP的RTTI和Java反射机制访问static private属性使用ABAP的RTTI和Java反射机制访问static private属性

import java.lang.reflect.Field;

public class Point {
    private int x;
    private int y;
    static private int count = 0;
    public Point(int x, int y){
        this.x = x;
        this.y = y;
        count++;
    }
    private static void accessStaticPrivate(Point point){
        Class classObject = point.getClass();
        try {
            Field countField = classObject.getDeclaredField("count");
            System.out.println("count: " + countField.get(point));
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException
                | IllegalAccessException e1 ) {
            e1.printStackTrace();
        } 
    }
    public static void main(String[] arg){
        Point a = new Point(1,2);
        accessStaticPrivate(a);
        
        Point b = new Point(1,3);
        accessStaticPrivate(b);
        
        Point c = new Point(1,4);
        accessStaticPrivate(c);
        
        Point d = new Point(1,5);
        accessStaticPrivate(d);
    }
}

使用ABAP的RTTI和Java反射机制访问static private属性Unlike RTTI in ABAP, Java reflection can sometimes lead to security issues, see one example how Java Singleton would be bypassed in blog Singleton bypass – ABAP and Java.