Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error using Byte Buddy on Android

I'm trying to use Byte Buddy library in Android but I get an error:

java.lang.IllegalStateException: This JVM's version string does not seem to be valid: 0

I have coded nothing yet, just:

ByteBuddy test = new ByteBuddy();

in my App.java

I have imported:

<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy</artifactId>
    <version>0.7.7</version>
</dependency>

but it didn't work, to I tried with:

<dependency>
    <groupId>net.bytebuddy</groupId>
    <artifactId>byte-buddy-android</artifactId>
    <version>0.7.7</version>
</dependency>

but I still get same error.

EDIT

I have put this line before initialize ByteBuddy:

  System.setProperty("java.version", "1.7.0_51");

But now I get this another error:

Caused by: java.lang.UnsupportedOperationException: can't load this type of class file.

for this code:

Class<?> dynamicType = new ByteBuddy(ClassFileVersion.JAVA_V6)
            .subclass(Object.class)
            .method(ElementMatchers.named("toString"))
            .intercept(FixedValue.value("Hello World!"))
            .make()
            .load(getClass().getClassLoader(), AndroidClassLoadingStrategy.Default.WRAPPER)
            .getLoaded();
like image 567
Héctor Avatar asked Dec 24 '15 10:12

Héctor


1 Answers

The error is because java.version returns 0 in Android (See section System Properties here - Comparison of Java and Android API)

Also, if you observe ByteBuddy ClassFileVersion

forCurrentJavaVersion() : This method checks for versionString which should return any valid Java/JDK version else it

throws IllegalStateException("This JVM's version string does not seem to be valid: " + versionString);

& since java.version is returning 0, it's throwing IllegalStateException.

Try to log this value:

String versionString = System.getProperty(JAVA_VERSION_PROPERTY);
Log.d(TAG, versionString);//retruns 0 here

hence workaround for this issue is to add

 System.setProperty(JAVA_VERSION_PROPERTY, "1.7.0_79");//add your jdk version here

before calling

ByteBuddy test = new ByteBuddy();

where JAVA_VERSION_PROPERTY is declared as:

 private static final String JAVA_VERSION_PROPERTY = "java.version";

Also dependency to use is:

<dependency>
<groupId>net.bytebuddy</groupId>
<artifactId>byte-buddy</artifactId>
<version>0.7.7</version>
</dependency>

Else if you are using studio, you can add

compile 'net.bytebuddy:byte-buddy:0.7.7'

to your app build.gradle.

Hope this will help solve your issue.

like image 150
Amrit Pal Singh Avatar answered Oct 31 '22 12:10

Amrit Pal Singh