简体   繁体   中英

In Android, how to invoke sun.misc.Unsafe methods using Java reflection?

Although there are similar questions (such as A , B and C ), their answers do not solve my problem.

I am using Android Studio 1.5.1 targeting Android API 18 (before Android KitKat 4.4, so I'm dealing with Dalvik, not ART runtime).

My questions are:

(1) When I use the following code, I can print a list of all sun.misc.Unsafe methods available in Android , so I think I have access to them using reflection but I do not know how to call them using reflection .

(2) If (1) is possible, how to find the magicNumber (in the code below) address using sun.misc.Unsafe methods in Android via reflection?

(3) If (1) is possible but (2) is not possible, how to put an integer number (say int test=123) in any native memory address and print its memory address using sun.misc.Unsafe methods in Android via reflection?

        String ClassName = "sun.misc.Unsafe";
        int magicNumber = 0x23420023 ;
    try {
        Class classToInvestigate = Class.forName(ClassName);
        Constructor[] aClassConstructors = classToInvestigate.getDeclaredConstructors();
        for(Constructor c : aClassConstructors){
            System.out.println("********************* constructor="+c);
        }

        Method[] aClassMethods = classToInvestigate.getDeclaredMethods();
        for(Method m : aClassMethods){
            System.out.println("********************* method="+m);

        }
        Field theUnsafe = classToInvestigate.getDeclaredField("THE_ONE");
        theUnsafe.setAccessible(true);
        Object unsafe = theUnsafe.get(null);

    } catch (ClassNotFoundException e) {
        // Class not found!
    }
    catch (Exception e) {
        // Unknown exception
    }

不幸的是, sun.misc.Unsafe类未包含在android标准库中,您应该在反射之间使用它,但是我发现了另一个解决方案:在我的库中的预编译直接代理类之间使用它: https : //github.com/iamironz/不安全的

该类将为您返回几乎所有现有JVM实现(包括Android(两个VM版本))上的Unsafe实例: https : //github.com/noctarius/tengi/blob/master/java/tengi-core/src/main/java/ com / noctarius / tengi / core / impl / UnsafeUtil.java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM