SlideShare ist ein Scribd-Unternehmen logo
1 von 26
Java byte code
in practice
0xCAFEBABE
source code
byte code
JVM
javac scalac groovyc jrubyc
JIT compilerinterpreter
class loader
creates
reads
runs
source code byte code
void foo() {
}
RETURNreturn; 0xB1
source code byte code
int foo() {
return 1 + 2;
}
ICONST_1
ICONST_2
IADD
operand stack 1
2
13
IRETURN
0x04
0x05
0x60
0xAC
source code byte code
ICONST_2
IADD
IRETURN
BIPUSH
int foo() {
return 11 + 2;
}
operand stack 11
2
1113
0x05
0x60
0xAC
0x10 110x0B
source code byte code
int foo(int i) {
return i + 1;
}
ILOAD_1
ICONST_1
IADD
IRETURN
operand stack
local variable array
1 : i
0 : this
i
1
ii + 1
0x1B
0x04
0x60
0xAC
source code byte code
long foo(long i) {
return i + 1L;
}
LLOAD_1
LCONST_1
LADD
LRETURN
operand stack
local variable array
2 : i (cn.)
1 : i
0 : this
i (cn.)
i
0x1F
0x0A
0x61
0xAD
i (cn.)
i
1L
1L (cn.)
i + 1L
i + 1L (cn.)
source code byte code
short foo(short i) {
return (short) (i + 1);
}
ILOAD_1
ICONST_1
IADD
I2S
IRETURN
operand stack
local variable array
1 : i
0 : this
1
iii + 1
0x1B
0x04
0x60
0x93
0xAC
source code byte code
pkg/Bar.class
void foo() {
return;
}
RETURN
package pkg;
class Bar {
}
constant pool (i.a. UTF-8)
0x0000
0x0000: foo
0x0001: ()V
0x0002: pkg/Bar
0xB1
0x0000 0x0000foo ()V()V0x0001
0x00000 1 10x0001
operand stack /////////////////
local variable array 0 : this
Java type JVM type (non-array) JVM descriptor stack slots
boolean
I
Z 1
byte B 1
short S 1
char C 1
int I 1
long L J 2
float F F 1
double D D 2
void - V 0
java.lang.Object A Ljava/lang/Object; 1
source code byte code
package pkg;
class Bar {
int foo(int i) {
return foo(i + 1);
}
}
ILOAD_1
ICONST_1
IADD
INVOKEVIRTUAL pkg/Bar foo (I)I
ALOAD_0
IRETURN
operand stack
local variable array
1 : i
0 : this
this
i
1
this
ii + 1
foo(i + 1)
0x2A
0x1B
0x04
0x60
0xAC
0xB6
constant pool
0x0002 0x0000 0x0001
INVOKESPECIAL
INVOKEVIRTUAL
INVOKESTATIC
INVOKEINTERFACE
INVOKEDYNAMIC
Invokes a static method.
pkg/Bar foo ()V
pkg/Bar foo ()V
Invokes the most-specific version of an inherited method on a non-interface class.
pkg/Bar foo ()V
Invokes a super class‘s version of an inherited method.
Invokes a “constructor method”.
Invokes a private method.
Invokes an interface default method (Java 8).
pkg/Bar foo ()V
Invokes an interface method.
(Similar to INVOKEVIRTUAL but without virtual method table index optimization.)
foo ()V bootstrap
Queries the given bootstrap method for locating a method implementation at runtime.
(MethodHandle: Combines a specific method and an INVOKE* instruction.)
void foo() {
???(); // invokedynamic
}
foo() ? qux()
bootstrap()
bar()
void foo() {
bar();
}
In theory, this could be achieved by using reflection. However, using invokedynamic
offers a more native approach. This is especially important when dealing with
primitive types (double boxing).
Used to implement lambda expressions, more important for dynamic languages.
interface Framework {
<T> Class<? extends T> secure(Class<T> type);
}
class Service {
@Secured(user = "ADMIN")
void deleteEverything() {
// delete everything...
}
}
@interface Secured {
String user();
}
class SecurityHolder {
static String user = "ANONYMOUS";
}
does not know aboutdepends on
discoversatruntime
class Service {
@Secured(user = "ADMIN")
void deleteEverything() {
if(!"ADMIN".equals(UserHolder.user)) {
throw new IllegalStateException("Wrong user");
}
// delete everything...
}
}
redefine class
(build time, agent)
create subclass
(Liskov substitution)
class SecuredService extends Service {
@Override
void deleteEverything() {
if(!"ADMIN".equals(UserHolder.user)) {
throw new IllegalStateException("Wrong user");
}
super.deleteEverything();
}
}
class Service {
@Secured(user = "ADMIN")
void deleteEverything() {
// delete everything...
}
}
The “black magic” prejudice.
var service = {
/* @Secured(user = "ADMIN") */
deleteEverything: function () {
// delete everything ...
}
}
function run(service) {
service.deleteEverything();
}
In dynamic languages (also those running on the JVM) this concept is applied a lot!
For framework implementors, type-safety is conceptually impossible.
But with type information available, we are at least able to fail fast when generating
code at runtime in case that types do not match.
No type, no problem.
(“duck typing”)
class Method {
Object invoke(Object obj,
Object... args)
throws IllegalAccessException,
IllegalArgumentException,
InvocationTargetException;
}
class Class {
Method getDeclaredMethod(String name,
Class<?>... parameterTypes)
throws NoSuchMethodException,
SecurityException;
}
Isn’t reflection meant for this?
Reflection implies neither type-safety nor a notion of fail-fast.
Note: there are no performance gains when using code generation over reflection!
Thus, runtime code generation only makes sense for user type enhancement: While
the framework code is less type safe, this type-unsafety does not spoil the user‘s code.
Class<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(named("toString"))
.intercept(value("Hello World!"))
.make()
.load(getClass().getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
assertThat(dynamicType.newInstance().toString(),
is("Hello World!"));
Byte Buddy: subclass creation
class MyInterceptor {
static String intercept() {
return "Hello World";
}
}
identifiesbestmatch
Class<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(named("toString"))
.intercept(to(MyInterceptor.class))
.make()
.load(getClass().getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
Byte Buddy: invocation delegation
Annotations that are not on the class path are ignored at runtime.
Thus, Byte Buddy’s classes can be used without Byte Buddy on the class path.
class MyInterceptor {
static String intercept(@Origin Method m) {
return "Hello World from " + m.getName();
}
}
Class<?> dynamicType = new ByteBuddy()
.subclass(Object.class)
.method(named("toString"))
.intercept(to(MyInterceptor.class))
.make()
.load(getClass().getClassLoader(),
ClassLoadingStrategy.Default.WRAPPER)
.getLoaded();
providesarguments
Byte Buddy: invocation delegation (2)
@Origin Method|Class<?>|String Provides caller information
@SuperCall Runnable|Callable<?> Allows super method call
@DefaultCall Runnable|Callable<?> Allows default method call
@AllArguments T[] Provides boxed method arguments
@Argument(index) T Provides argument at the given index
@This T Provides caller instance
@Super T Provides super method proxy
Byte Buddy: dependency injection
class Foo {
String bar() { return "bar"; }
}
Foo foo = new Foo();
new ByteBuddy()
.redefine(Foo.class)
.method(named("bar"))
.intercept(value("Hello World!"))
.make()
.load(Foo.class.getClassLoader(),
ClassReloadingStrategy.installedAgent());
assertThat(foo.bar(), is("Hello World!"));
The instrumentation API does not allow introduction of new methods.
This might change with JEP-159: Enhanced Class Redefiniton.
Byte Buddy: runtime Hot Swap
class Foo {
String bar() { return "bar"; }
}
assertThat(new Foo().bar(), is("Hello World!"));
public static void premain(String arguments,
Instrumentation instrumentation) {
new AgentBuilder.Default()
.rebase(named("Foo"))
.transform( (builder, type) -> builder
.method(named("bar"))
.intercept(value("Hello World!"));
)
.installOn(instrumentation);
}
Byte Buddy: Java agents
Java virtual
machine
[stack, JIT]
Dalvik virtual
machine
[register, JIT]
Android
runtime
[register, AOT]
Android makes things more complicated.
Solution: Embed the Android SDK’s dex compiler (Apache 2.0 license).
Unfortunately, no recent version central repository deployments of Android SDK.
Byte Buddy cglib Javassist Java proxy
(1) 60.995 234.488 145.412 68.706
(2a) 153.800 804.000 706.878 973.650
(2b) 0.001 0.002 0.009 0.005
(3a) 172.126
1’850.567
1’480.525 625.778 n/a
(3b) 0.002
0.003
0.019 0.027 n/a
All benchmarks run with JMH, source code: https://github.com/raphw/byte-buddy
(1) Extending the Object class without any methods but with a default constructor
(2a) Implementing an interface with 18 methods, method stubs
(2b) Executing a method of this interface
(3a) Extending a class with 18 methods, super method invocation
(3b) Executing a method of this class
http://rafael.codes
@rafaelcodes
http://documents4j.com
https://github.com/documents4j/documents4j
http://bytebuddy.net
https://github.com/raphw/byte-buddy

Weitere ähnliche Inhalte

Was ist angesagt?

Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 

Was ist angesagt? (20)

Byte code field report
Byte code field reportByte code field report
Byte code field report
 
The Java memory model made easy
The Java memory model made easyThe Java memory model made easy
The Java memory model made easy
 
Bytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASMBytecode manipulation with Javassist and ASM
Bytecode manipulation with Javassist and ASM
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Java and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystemJava and OpenJDK: disecting the ecosystem
Java and OpenJDK: disecting the ecosystem
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
An Overview of Project Jigsaw
An Overview of Project JigsawAn Overview of Project Jigsaw
An Overview of Project Jigsaw
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Sailing with Java 8 Streams
Sailing with Java 8 StreamsSailing with Java 8 Streams
Sailing with Java 8 Streams
 
Java Concurrency
Java ConcurrencyJava Concurrency
Java Concurrency
 
Learning Java 1 – Introduction
Learning Java 1 – IntroductionLearning Java 1 – Introduction
Learning Java 1 – Introduction
 
Code generation for alternative languages
Code generation for alternative languagesCode generation for alternative languages
Code generation for alternative languages
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Project Coin
Project CoinProject Coin
Project Coin
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Java 14 features
Java 14 featuresJava 14 features
Java 14 features
 

Ähnlich wie Java byte code in practice

Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
Technopark
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Anton Arhipov
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
Mario Fusco
 

Ähnlich wie Java byte code in practice (20)

Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Nice to meet Kotlin
Nice to meet KotlinNice to meet Kotlin
Nice to meet Kotlin
 
Griffon @ Svwjug
Griffon @ SvwjugGriffon @ Svwjug
Griffon @ Svwjug
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Wrapper class
Wrapper classWrapper class
Wrapper class
 
Java осень 2012 лекция 2
Java осень 2012 лекция 2Java осень 2012 лекция 2
Java осень 2012 лекция 2
 
Swift - One step forward from Obj-C
Swift -  One step forward from Obj-CSwift -  One step forward from Obj-C
Swift - One step forward from Obj-C
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
Multithreading in Java
Multithreading in JavaMultithreading in Java
Multithreading in Java
 
RxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камниRxJava и Android. Плюсы, минусы, подводные камни
RxJava и Android. Плюсы, минусы, подводные камни
 
Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012Binary patching for fun and profit @ JUG.ru, 25.02.2012
Binary patching for fun and profit @ JUG.ru, 25.02.2012
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Java interface
Java interfaceJava interface
Java interface
 
EcmaScript unchained
EcmaScript unchainedEcmaScript unchained
EcmaScript unchained
 
Java VS Python
Java VS PythonJava VS Python
Java VS Python
 
Kotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime PerformanceKotlin Bytecode Generation and Runtime Performance
Kotlin Bytecode Generation and Runtime Performance
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf MilanFrom Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
From Java to Kotlin beyond alt+shift+cmd+k - Kotlin Community Conf Milan
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 

Java byte code in practice

  • 1. Java byte code in practice
  • 2. 0xCAFEBABE source code byte code JVM javac scalac groovyc jrubyc JIT compilerinterpreter class loader creates reads runs
  • 3. source code byte code void foo() { } RETURNreturn; 0xB1
  • 4. source code byte code int foo() { return 1 + 2; } ICONST_1 ICONST_2 IADD operand stack 1 2 13 IRETURN 0x04 0x05 0x60 0xAC
  • 5. source code byte code ICONST_2 IADD IRETURN BIPUSH int foo() { return 11 + 2; } operand stack 11 2 1113 0x05 0x60 0xAC 0x10 110x0B
  • 6. source code byte code int foo(int i) { return i + 1; } ILOAD_1 ICONST_1 IADD IRETURN operand stack local variable array 1 : i 0 : this i 1 ii + 1 0x1B 0x04 0x60 0xAC
  • 7. source code byte code long foo(long i) { return i + 1L; } LLOAD_1 LCONST_1 LADD LRETURN operand stack local variable array 2 : i (cn.) 1 : i 0 : this i (cn.) i 0x1F 0x0A 0x61 0xAD i (cn.) i 1L 1L (cn.) i + 1L i + 1L (cn.)
  • 8. source code byte code short foo(short i) { return (short) (i + 1); } ILOAD_1 ICONST_1 IADD I2S IRETURN operand stack local variable array 1 : i 0 : this 1 iii + 1 0x1B 0x04 0x60 0x93 0xAC
  • 9. source code byte code pkg/Bar.class void foo() { return; } RETURN package pkg; class Bar { } constant pool (i.a. UTF-8) 0x0000 0x0000: foo 0x0001: ()V 0x0002: pkg/Bar 0xB1 0x0000 0x0000foo ()V()V0x0001 0x00000 1 10x0001 operand stack ///////////////// local variable array 0 : this
  • 10. Java type JVM type (non-array) JVM descriptor stack slots boolean I Z 1 byte B 1 short S 1 char C 1 int I 1 long L J 2 float F F 1 double D D 2 void - V 0 java.lang.Object A Ljava/lang/Object; 1
  • 11. source code byte code package pkg; class Bar { int foo(int i) { return foo(i + 1); } } ILOAD_1 ICONST_1 IADD INVOKEVIRTUAL pkg/Bar foo (I)I ALOAD_0 IRETURN operand stack local variable array 1 : i 0 : this this i 1 this ii + 1 foo(i + 1) 0x2A 0x1B 0x04 0x60 0xAC 0xB6 constant pool 0x0002 0x0000 0x0001
  • 12. INVOKESPECIAL INVOKEVIRTUAL INVOKESTATIC INVOKEINTERFACE INVOKEDYNAMIC Invokes a static method. pkg/Bar foo ()V pkg/Bar foo ()V Invokes the most-specific version of an inherited method on a non-interface class. pkg/Bar foo ()V Invokes a super class‘s version of an inherited method. Invokes a “constructor method”. Invokes a private method. Invokes an interface default method (Java 8). pkg/Bar foo ()V Invokes an interface method. (Similar to INVOKEVIRTUAL but without virtual method table index optimization.) foo ()V bootstrap Queries the given bootstrap method for locating a method implementation at runtime. (MethodHandle: Combines a specific method and an INVOKE* instruction.)
  • 13. void foo() { ???(); // invokedynamic } foo() ? qux() bootstrap() bar() void foo() { bar(); } In theory, this could be achieved by using reflection. However, using invokedynamic offers a more native approach. This is especially important when dealing with primitive types (double boxing). Used to implement lambda expressions, more important for dynamic languages.
  • 14. interface Framework { <T> Class<? extends T> secure(Class<T> type); } class Service { @Secured(user = "ADMIN") void deleteEverything() { // delete everything... } } @interface Secured { String user(); } class SecurityHolder { static String user = "ANONYMOUS"; } does not know aboutdepends on discoversatruntime
  • 15. class Service { @Secured(user = "ADMIN") void deleteEverything() { if(!"ADMIN".equals(UserHolder.user)) { throw new IllegalStateException("Wrong user"); } // delete everything... } } redefine class (build time, agent) create subclass (Liskov substitution) class SecuredService extends Service { @Override void deleteEverything() { if(!"ADMIN".equals(UserHolder.user)) { throw new IllegalStateException("Wrong user"); } super.deleteEverything(); } } class Service { @Secured(user = "ADMIN") void deleteEverything() { // delete everything... } }
  • 16. The “black magic” prejudice. var service = { /* @Secured(user = "ADMIN") */ deleteEverything: function () { // delete everything ... } } function run(service) { service.deleteEverything(); } In dynamic languages (also those running on the JVM) this concept is applied a lot! For framework implementors, type-safety is conceptually impossible. But with type information available, we are at least able to fail fast when generating code at runtime in case that types do not match. No type, no problem. (“duck typing”)
  • 17. class Method { Object invoke(Object obj, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException; } class Class { Method getDeclaredMethod(String name, Class<?>... parameterTypes) throws NoSuchMethodException, SecurityException; } Isn’t reflection meant for this? Reflection implies neither type-safety nor a notion of fail-fast. Note: there are no performance gains when using code generation over reflection! Thus, runtime code generation only makes sense for user type enhancement: While the framework code is less type safe, this type-unsafety does not spoil the user‘s code.
  • 18. Class<?> dynamicType = new ByteBuddy() .subclass(Object.class) .method(named("toString")) .intercept(value("Hello World!")) .make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); assertThat(dynamicType.newInstance().toString(), is("Hello World!")); Byte Buddy: subclass creation
  • 19. class MyInterceptor { static String intercept() { return "Hello World"; } } identifiesbestmatch Class<?> dynamicType = new ByteBuddy() .subclass(Object.class) .method(named("toString")) .intercept(to(MyInterceptor.class)) .make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); Byte Buddy: invocation delegation
  • 20. Annotations that are not on the class path are ignored at runtime. Thus, Byte Buddy’s classes can be used without Byte Buddy on the class path. class MyInterceptor { static String intercept(@Origin Method m) { return "Hello World from " + m.getName(); } } Class<?> dynamicType = new ByteBuddy() .subclass(Object.class) .method(named("toString")) .intercept(to(MyInterceptor.class)) .make() .load(getClass().getClassLoader(), ClassLoadingStrategy.Default.WRAPPER) .getLoaded(); providesarguments Byte Buddy: invocation delegation (2)
  • 21. @Origin Method|Class<?>|String Provides caller information @SuperCall Runnable|Callable<?> Allows super method call @DefaultCall Runnable|Callable<?> Allows default method call @AllArguments T[] Provides boxed method arguments @Argument(index) T Provides argument at the given index @This T Provides caller instance @Super T Provides super method proxy Byte Buddy: dependency injection
  • 22. class Foo { String bar() { return "bar"; } } Foo foo = new Foo(); new ByteBuddy() .redefine(Foo.class) .method(named("bar")) .intercept(value("Hello World!")) .make() .load(Foo.class.getClassLoader(), ClassReloadingStrategy.installedAgent()); assertThat(foo.bar(), is("Hello World!")); The instrumentation API does not allow introduction of new methods. This might change with JEP-159: Enhanced Class Redefiniton. Byte Buddy: runtime Hot Swap
  • 23. class Foo { String bar() { return "bar"; } } assertThat(new Foo().bar(), is("Hello World!")); public static void premain(String arguments, Instrumentation instrumentation) { new AgentBuilder.Default() .rebase(named("Foo")) .transform( (builder, type) -> builder .method(named("bar")) .intercept(value("Hello World!")); ) .installOn(instrumentation); } Byte Buddy: Java agents
  • 24. Java virtual machine [stack, JIT] Dalvik virtual machine [register, JIT] Android runtime [register, AOT] Android makes things more complicated. Solution: Embed the Android SDK’s dex compiler (Apache 2.0 license). Unfortunately, no recent version central repository deployments of Android SDK.
  • 25. Byte Buddy cglib Javassist Java proxy (1) 60.995 234.488 145.412 68.706 (2a) 153.800 804.000 706.878 973.650 (2b) 0.001 0.002 0.009 0.005 (3a) 172.126 1’850.567 1’480.525 625.778 n/a (3b) 0.002 0.003 0.019 0.027 n/a All benchmarks run with JMH, source code: https://github.com/raphw/byte-buddy (1) Extending the Object class without any methods but with a default constructor (2a) Implementing an interface with 18 methods, method stubs (2b) Executing a method of this interface (3a) Extending a class with 18 methods, super method invocation (3b) Executing a method of this class