Java Reflection API@KonaTechAdda
Md Imran Hasan Hira
Software Engineer
Kona Software Lab Ltd.
http://bd.linkedin.com/in/imranhasanhira
https://www.facebook.com/KonaSoftwarehttps://www.linkedin.com/company/kona-software-lab-ltd-
Outlines
• Design of reflection API
• Getting class
• Encoding class names
• Examples
• Modifiers
• Drawbacks
What & Why• Logics vs configurations
• Dependency Injections
• Methods param suggestion
• Build tools
• Spring…
• Runtime Code generation
• Bytecode Manipulation
Java Reflection
Java Ob
ject
Basic Idea
• Accessing a field in runtime• Find a class
• Instantiate a object form the class
• Find it’s field
• Set value of the field on that object
• Calling a method in runtime• Find a class
• Instantiate a object form the class
• Find it’s method
• Invoke the method (with/without parameter)
• Get the returned value
Necessary Classes
java.lang.Class
java.lang.reflection.Method
java.lang.reflection.Field
java.lang.reflection.Constructor
java.lang.reflection.Modifier
java.lang.reflection.Parameter
“Class” ক্লাশের public methods
Class
Including private
Including Inherited
Own + private, no inherited
Own + inherited, except private
“Constructor” & “Method”
Constructor
Method
“Field” & “Modifier”
Field
Modifier
Ways to get class
1. With the static field*
2. Providing full class path
3. getClass() method
Classpath encoding schema*
byte
char
MyClass
MyClass[]
byte[]
“B”
“C”
“Lcom.mypackage.MyClass;”
“[Lcom.myPackage.MyClass;”
“[B”
byte[][] “[[B”
Finding fields upto superclass
new Manager();
Data Parsing
Data Parsing (Dynamic)
Method Calling
Name: Default name, Age: 0
Name: Dynamic name, Age: 0
Java Ob
ject
Reflection Drawbacks
• Performance overhead • Dynamically type resolutions occlude JVM optimizations.
• Should be avoided in parts of code in performance sensitive applications
*Taken from a article of Dennis Sosnoski,
Reflection Drawbacks
• Performance overhead • Dynamically type resolutions occlude JVM optimizations.
• Should be avoided in parts of code in performance sensitive applications
• Security Restrictions• Requires a runtime permission, so your code may not run in a restricted
security context.
• Exposure of Internals• Accessing private fields and methods
• Reflective code breaks abstractions*
References
Article from Oracle -
https://docs.oracle.com/javase/tutorial/reflect/
http://docs.oracle.com/javase/8/docs/api/index.html?java/lang/Class.html
Dennis Sosnoski’s Article on Reflection -http://www.ibm.com/developerworks/java/library/j-dyn0603/index.html
Source Code Snippets -
https://github.com/imranhasanhira/java-reflection-annotation-test
Thank You