Error using Byte Buddy on Android

I try to use the Byte Buddy library on Android, but I get an error:

java.lang.IllegalStateException: this line of JVM version does not seem valid: 0

I haven't encoded anything yet, just:

ByteBuddy test = new ByteBuddy(); 

in my App.java

I imported:

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

but this did not work, i tried:

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

but I still get the same error.

EDIT

I put this line before initializing ByteBuddy:

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

But now I get the following error:

Called: java.lang.UnsupportedOperationException: Unable to 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(); 
+5
source share
1 answer

The error is that java.version returns 0 in Android (see the "System Properties" section here - Comparing Java and Android APIs )

Also, if you are observing ByteBuddy ClassFileVersion

forCurrentJavaVersion () : this method checks for a versionString that should return any valid Java / JDK else version

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

& since java.version returns 0 , it throws an IllegalStateException .

Try writing this value:

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

Therefore, a workaround for this problem 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"; 

The dependency is also used:

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

If you are using a studio, you can add

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

into your build.gradle application.

Hope this helps solve your problem.

+3
source

Source: https://habr.com/ru/post/1239119/


All Articles