SlideShare a Scribd company logo
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Java Reflection :
Java Reflection provides ability to inspect and modify the runtime behavior of application. Using java reflection we
can inspect a class, interface, enum, get their structure, methods and fields information at runtime even though
class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods,
change field values. Some of the frameworks that use java reflection are, Junit, Spring, Tomcat , Eclipse, Struts,
Hibernate.
Where it is used:
o IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc.
o Debugger
o Test Tools etc.
We should not use reflection in normal programming where we already have access to the classes and interfaces
because of following drawbacks:
 Poor Performance – Since java reflection resolve the types dynamically, it involves processing like
scanning the classpath to find the class to load, causing slow performance.
 Security Restrictions – Reflection requires runtime permissions that might not be available for system
running under security manager. This can cause you application to fail at runtime because of security
manager.
 Security Issues – Using reflection we can access part of code that we are not supposed to access, for
example we can access private fields of a class and change it’s value. This can be a serious security threat
and cause your application to behave abnormally.
 High Maintenance – Reflection code is hard to understand and debug, also any issues with the code can’t
be found at compile time because the classes might not be available, making it less flexible and hard to
maintain.
Getting Class Object:
Before you can do any inspection on a class you need to obtain its java.lang.Class object. All types in Java
including the primitive types (int, long, float etc.) and arrays have an associated Class object.
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
There are 3 ways to get the instance of Class class. They are as follows:
o the .class syntax
o getClass() method of Object class
o forName() method of Class class
1) The .class syntax:
If a type is available but there is no instance then it is possible to obtain a Class by appending
".class" to the name of the type.It can be used for primitive data type also.
package com.behsazan;
class TestClass {.… }
Class aClass = TestClass.class;
String className = aClass.getName();
// for primitive Types
Class aClass = boolean.class;
Class bClass = int.class;
String className = aClass.getName();
2) getClass() method:
It should be used if you know the type.
TestClass testClassObject =new TestClass();
Class aClass = testClassObject.getClass();
boolean myVar;
Class aClass = myVar.getClass(); // compile-time error
3) forName() method:
If you don't know the name at compile time, but have the class name as a string at runtime,
you can do like this:
Class aClass = Class.forName("com.behsazan.TestClass");
Superclass
From the Class object you can access the superclass of the class. The superclass class object is a Class object
like any other, so you can continue doing class reflection on that too. Here is how:
Class superclass = aClass.getSuperclass();
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Constructors
You can access the constructors of a class like this:
Constructor[] constructors = aClass.getConstructors();
Methods
You can access the methods of a class like this:
Method[] method = aClass.getMethods(); // get List of methods
Method[] method = aClass.getDeclaredMethods();
Method method = aClass.getMethod("methodName", methodParams);
Method method = aClass.getDeclaredMethod("methodName", methodParams);
getMethod VS getDeclaredMethod:
‫تفاوت‬getMethod‫ﺑا‬getDeclaredMethod‫تاﺑع‬ ‫در‬ ‫كه‬ ‫كه‬ ‫است‬ ‫اين‬ ‫در‬getMethod‫در‬ ‫متد‬ ‫دنبال‬ ‫ﺑه‬ ،‫نكند‬ ‫پيدا‬ ‫را‬ ‫متد‬ ‫جاري‬ ‫كﻼس‬ ‫در‬ ‫اگر‬
‫كﻼس‬super.‫گردد‬ ‫مي‬ ‫آن‬
Fields
You can access the fields (member variables) of a class like this:
Field[] fields = aClass.getFields();
Field[] fields = aClass.getDeclaredFields();
Field field = aClass. getField(("fieldName");
Field field = aClass. getDeclaredField(("fieldName");
Package Info
You can obtain information about the package from a Class object like this:
Class aClass = ... //obtain Class object. See prev. section
Package package = aClass.getPackage();
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Modifiers
The class modifiers are the keywords "public", "private", "static" etc. The modifiers are packed into an int
where each modifier is a flag bit that is either set or cleared. You can obtain the class modifiers like this:
Class aClass = ... //obtain Class object
int modifiers = aClass.getModifiers();
You can check the modifiers using these methods in the class java.lang.reflect.Modifier:
Modifier.isAbstract(int modifiers)
Modifier.isFinal(int modifiers)
Modifier.isInterface(int modifiers)
Modifier.isNative(int modifiers)
Modifier.isPrivate(int modifiers)
Modifier.isProtected(int modifiers)
Modifier.isPublic(int modifiers)
Modifier.isStatic(int modifiers)
Modifier.isStrict(int modifiers)
Modifier.isSynchronized(int modifiers)
Modifier.isTransient(int modifiers)
Modifier.isVolatile(int modifiers
Example:
Public class SimpleClass{
public void method1 (){
System.out.println("method1() was called!");
}
public void method2 (String tempStr){
System.out.println("method2() was called!" + tempStr);
}
public void method3 (int tempInt){
System.out.println("method3() was called!" + tempInt);
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
}
}
public static void main(String args[]) {
//no paramater
Class noparams[] = {};
//String parameter
Class[] paramString = new Class[1];
paramString[0] = String.class;
//int parameter
Class[] paramInt = new Class[1];
paramInt[0] = Integer.TYPE;
try {
Class tempClass = Class.forName("com.behsazan.SimpleClass");
Object obj = tempClass.newInstance();
//call the method1 method
Method method = cls.getDeclaredMethod("method1", noparams);
method.invoke(obj, null);
//call the method2 with String Inputs
Method method = cls.getDeclaredMethod("method2", paramString);
method.invoke(obj, new String("inputParams"));
//call the method3 with Interger Inputs
Method method = cls.getDeclaredMethod("method3", paramInt);
method.invoke(obj, 1234);
} catch (ClassNotFoundException ee) {
System.out.println("Couldn't find class 'SimpleClass'");
System.exit(1);
}
}
TYPE Field for Primitive Type Wrappers
The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type;
however there is another way to acquire the Class. Each of the primitive types and void has a wrapper class
in java.lang that is used for boxing of primitive types to reference types. Each wrapper class contains a field
named TYPE which is equal to the Class for the primitive type being wrapped.
Class c = Double.TYPE;
is identical to
Class c = double.class.
Class c = Void.TYPE;
is identical to
Class c = void.class.
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Reflection – Arrays:
Working with arrays via Java Reflection is done using the java.lang.reflect.Array class.
Creating Arrays
Creating arrays via Java Reflection is done using the java.lang.reflect.Array class.
1. // This code sample creates an array of type int (int.class parameter) and size of 3
int[] intArray = (int[]) Array.newInstance(int.class, 3);
2. int dimensions[] = {3, 4};
int twoDimensionalIntArray[][] = (int[][])Array.newInstance(int.class, dimensions);
Accessing Arrays
int[] intArray = (int[]) Array.newInstance(int.class, 3);
Array.set(intArray, 0, 123);
Array.set(intArray, 1, 456);
Array.set(intArray, 2, 789);
System.out.println("intArray size = " + Array. getLength(intArray));
System.out.println("intArray[0] = " + Array.get(intArray, 0));
System.out.println("intArray[2] = " + Array.get(intArray, 2));
Sample Result:
intArray size = 3
intArray[0] = 123
intArray[2] = 789
Obtaining the Class Object of an Array
1. with .class Syntax:
Class intArrayClass = int[].class;
Class doubleArrayClass = double[].class;
Class stringTwoDimensionalArrayClass = String[][].class;
2. Using Class.forName:
Class intArray = Class.forName("[I"); // identical to int[].class
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Class cDoubleArray = Class.forName("[D"); // identical to double[].class
Class cStringArray = Class.forName("[[Ljava.lang.String;"); // identical to String[][].class
Obtaining the Component Type of an Array
Once you have obtained the Class object for an array you can access its component type via the
Class.getComponentType() method.
The component type is the type of the items in the array. For instance, the component type of an int[] array
is the int.class Class object. The component type of a String[] array is the java.lang.String Class object.
Example1:
String[] strings = new String[3];
Class stringArrayClass = strings.getClass();
Class stringArrayComponentType = stringArrayClass.getComponentType();
System.out.println(stringArrayComponentType); // prints : "java.lang.String"
Example2:
int[] object = {1,2,3};
Class aClass = object.getClass();
if (aClass.isArray()) {
Class elementType = aClass.getComponentType();
System.out.println("Array of: " + elementType); // prints : Array of: int
}
Example3:
import java.lang.reflect.Array;
public class ReflectionHelloWorld {
public static void main(String[] args) {
int[] intArray = { 1, 2, 3, 4, 5 };
int[] newIntArray = (int[]) changeArraySize(intArray, 10);
print(newIntArray);
String[] atr = { "a", "b", "c", "d", "e" };
String[] str1 = (String[]) changeArraySize(atr, 10);
print(str1);
}
// change array size
public static Object changeArraySize(Object obj, int len) {
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
Class<?> arr = obj.getClass().getComponentType();
Object newArray = Array.newInstance(arr, len);
//do array copy
int co = Array.getLength(obj);
System.arraycopy(obj, 0, newArray, 0, co);
return newArray;
}
// print
public static void print(Object obj) {
Class<?> c = obj.getClass();
if (!c.isArray()) {
return;
}
System.out.println("nArray length: " + Array.getLength(obj));
for (int i = 0; i < Array.getLength(obj); i++) {
System.out.print(Array.get(obj, i) + " ");
}
}
}
reflection & Generics:
public class MyGenericClass<T extends Number> {
private String name = "Default Name";
private int age;
private T counter;
public MyGenericClass(String tempVar) {
this.name = tempVar;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public T getCounter() {
return counter;
}
public void setCounter(T counter) {
Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid
this.counter = counter;
}
public < E > void printArray(E[] inputArray ) {
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println("");
}
}
public static void main(String[] args) {
try {
Class<?> aClass = Class.forName("MyGenericClass");
Constructor constructorMethod = aClass.getConstructor(String.class);
Object myGenericClassObj = constructorMethod.newInstance("This is Reflection Test.");
Method getMyVarMethod = myGenericClassObj.getClass().getMethod("getName", null);
System.out.println(getMyVarMethod.invoke(myGenericClassObj));
Method setAgeMethod = myGenericClassObj.getClass().getMethod("setAge", Integer.TYPE);
setAgeMethod.invoke(myGenericClassObj,38);
Method getAgeMethod = myGenericClassObj.getClass().getMethod("getAge", null);
Object returnObj = getAgeMethod.invoke(myGenericClassObj);
System.out.println("The age is : " + returnObj.toString());
Method setCounterMethod = myGenericClassObj.getClass().getMethod("setCounter", Number.class);
setCounterMethod.invoke(myGenericClassObj,1000);
Method getCounterMethod = myGenericClassObj.getClass().getMethod("getCounter", null);
returnObj = getCounterMethod.invoke(myGenericClassObj);
System.out.println("Counter is : " + returnObj.toString());
Method printArrMethod = myGenericClassObj.getClass().getMethod("printArray", Object[].class);
Object[] nums = {1,2,3};
String[] strs = { "str1", "str2"};
Object[] objs = {10, "a", 20 , "b",30, "c"};
printArrMethod.invoke(myGenericClassObj,new Object[]{ nums });
printArrMethod.invoke(myGenericClassObj,new Object[]{ strs });
printArrMethod.invoke(myGenericClassObj,new Object[]{ objs });
}
catch (Exception e){
System.out.print(e.getMessage());
}
}

More Related Content

What's hot (20)

PPT
Most Asked Java Interview Question and Answer
TOPS Technologies
 
PDF
Java multi threading and synchronization
rithustutorials
 
PPT
Object and Classes in Java
backdoor
 
PPT
Object Oriented Programming with Java
backdoor
 
DOCX
Java cheat sheet
Saifur Rahman
 
PDF
Advance java kvr -satya
Satya Johnny
 
PDF
Object Oriented Programming in PHP
Lorna Mitchell
 
PDF
02 basic java programming and operators
Danairat Thanabodithammachari
 
PDF
Java Programming Guide Quick Reference
FrescatiStory
 
PDF
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
PPS
Introduction to class in java
kamal kotecha
 
PPTX
Object+oriented+programming+in+java
Ye Win
 
PDF
201 core java interview questions oo ps interview questions - javatpoint
ravi tyagi
 
PDF
Java Cheat Sheet
GlowTouch
 
PPT
Java Tut1
guest5c8bd1
 
PPTX
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
PPTX
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
PPTX
Unit3 part1-class
DevaKumari Vijay
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PDF
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 
Most Asked Java Interview Question and Answer
TOPS Technologies
 
Java multi threading and synchronization
rithustutorials
 
Object and Classes in Java
backdoor
 
Object Oriented Programming with Java
backdoor
 
Java cheat sheet
Saifur Rahman
 
Advance java kvr -satya
Satya Johnny
 
Object Oriented Programming in PHP
Lorna Mitchell
 
02 basic java programming and operators
Danairat Thanabodithammachari
 
Java Programming Guide Quick Reference
FrescatiStory
 
Java Programming - 04 object oriented in java
Danairat Thanabodithammachari
 
Introduction to class in java
kamal kotecha
 
Object+oriented+programming+in+java
Ye Win
 
201 core java interview questions oo ps interview questions - javatpoint
ravi tyagi
 
Java Cheat Sheet
GlowTouch
 
Java Tut1
guest5c8bd1
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
Sagar Verma
 
Unit3 part3-packages and interfaces
DevaKumari Vijay
 
Unit3 part1-class
DevaKumari Vijay
 
Core java complete ppt(note)
arvind pandey
 
Java OOP Programming language (Part 5) - Inheritance
OUM SAOKOSAL
 

Similar to Java Reflection (20)

PPTX
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
PPTX
Object oriented concepts
Gousalya Ramachandran
 
PPTX
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
PPTX
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
PPT
Chapter 8 Inheritance
OUM SAOKOSAL
 
PPTX
inheritance.pptx
sonukumarjha12
 
PPTX
Inheritance in java computer programming app
figeman282
 
PPTX
19 reflection
dhrubo kayal
 
PDF
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
PPTX
Detailed_description_on_java_ppt_final.pptx
technicaljd3
 
PPTX
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
PPT
Reflection
Piyush Mittal
 
PDF
Adv kvr -satya
Jyothsna Sree
 
PPT
Java Reflection
elliando dias
 
PPTX
03 object-classes-pbl-4-slots
mha4
 
PPTX
03 object-classes-pbl-4-slots
mha4
 
PDF
Java scjp-part1
Raghavendra V Gayakwad
 
PPTX
Basics to java programming and concepts of java
1747503gunavardhanre
 
PPT
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
PPT
Sonu wiziq
Sonu WIZIQ
 
Java Reflection Concept and Working
Software Productivity Strategists, Inc
 
Object oriented concepts
Gousalya Ramachandran
 
Introduction of Object Oriented Programming Language using Java. .pptx
Poonam60376
 
Modules 333333333³3444444444444444444.pptx
radhikacordise
 
Chapter 8 Inheritance
OUM SAOKOSAL
 
inheritance.pptx
sonukumarjha12
 
Inheritance in java computer programming app
figeman282
 
19 reflection
dhrubo kayal
 
Advanced java jee material by KV Rao sir
AVINASH KUMAR
 
Detailed_description_on_java_ppt_final.pptx
technicaljd3
 
UNIT 3- Java- Inheritance, Multithreading.pptx
shilpar780389
 
Reflection
Piyush Mittal
 
Adv kvr -satya
Jyothsna Sree
 
Java Reflection
elliando dias
 
03 object-classes-pbl-4-slots
mha4
 
03 object-classes-pbl-4-slots
mha4
 
Java scjp-part1
Raghavendra V Gayakwad
 
Basics to java programming and concepts of java
1747503gunavardhanre
 
Corejava Training in Bangalore Tutorial
rajkamaltibacademy
 
Sonu wiziq
Sonu WIZIQ
 
Ad

More from Hamid Ghorbani (13)

PDF
Spring aop
Hamid Ghorbani
 
PDF
Spring boot jpa
Hamid Ghorbani
 
PDF
Spring mvc
Hamid Ghorbani
 
PDF
Payment Tokenization
Hamid Ghorbani
 
PDF
Reactjs Basics
Hamid Ghorbani
 
PDF
Rest web service
Hamid Ghorbani
 
PDF
Java I/o streams
Hamid Ghorbani
 
PDF
Java Generics
Hamid Ghorbani
 
PDF
Java collections
Hamid Ghorbani
 
PDF
IBM Integeration Bus(IIB) Fundamentals
Hamid Ghorbani
 
PDF
ESB Overview
Hamid Ghorbani
 
PDF
Spring security configuration
Hamid Ghorbani
 
PDF
SOA & ESB in banking systems(Persian language)
Hamid Ghorbani
 
Spring aop
Hamid Ghorbani
 
Spring boot jpa
Hamid Ghorbani
 
Spring mvc
Hamid Ghorbani
 
Payment Tokenization
Hamid Ghorbani
 
Reactjs Basics
Hamid Ghorbani
 
Rest web service
Hamid Ghorbani
 
Java I/o streams
Hamid Ghorbani
 
Java Generics
Hamid Ghorbani
 
Java collections
Hamid Ghorbani
 
IBM Integeration Bus(IIB) Fundamentals
Hamid Ghorbani
 
ESB Overview
Hamid Ghorbani
 
Spring security configuration
Hamid Ghorbani
 
SOA & ESB in banking systems(Persian language)
Hamid Ghorbani
 
Ad

Recently uploaded (20)

PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
PPTX
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
PDF
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PPTX
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
PPTX
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PPTX
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PPTX
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
PDF
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
Technical-Careers-Roadmap-in-Software-Market.pdf
Hussein Ali
 
Change Common Properties in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Empowering Asian Contributions: The Rise of Regional User Groups in Open Sour...
Shane Coughlan
 
Driver Easy Pro 6.1.1 Crack Licensce key 2025 FREE
utfefguu
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Coefficient of Variance in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Generic or Specific? Making sensible software design decisions
Bert Jan Schrijver
 
Help for Correlations in IBM SPSS Statistics.pptx
Version 1 Analytics
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
Hardware(Central Processing Unit ) CU and ALU
RizwanaKalsoom2
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
AEM User Group: India Chapter Kickoff Meeting
jennaf3
 
Download Canva Pro 2025 PC Crack Full Latest Version
bashirkhan333g
 

Java Reflection

  • 1. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid Java Reflection : Java Reflection provides ability to inspect and modify the runtime behavior of application. Using java reflection we can inspect a class, interface, enum, get their structure, methods and fields information at runtime even though class is not accessible at compile time. We can also use reflection to instantiate an object, invoke it’s methods, change field values. Some of the frameworks that use java reflection are, Junit, Spring, Tomcat , Eclipse, Struts, Hibernate. Where it is used: o IDE (Integrated Development Environment) e.g. Eclipse, MyEclipse, NetBeans etc. o Debugger o Test Tools etc. We should not use reflection in normal programming where we already have access to the classes and interfaces because of following drawbacks:  Poor Performance – Since java reflection resolve the types dynamically, it involves processing like scanning the classpath to find the class to load, causing slow performance.  Security Restrictions – Reflection requires runtime permissions that might not be available for system running under security manager. This can cause you application to fail at runtime because of security manager.  Security Issues – Using reflection we can access part of code that we are not supposed to access, for example we can access private fields of a class and change it’s value. This can be a serious security threat and cause your application to behave abnormally.  High Maintenance – Reflection code is hard to understand and debug, also any issues with the code can’t be found at compile time because the classes might not be available, making it less flexible and hard to maintain. Getting Class Object: Before you can do any inspection on a class you need to obtain its java.lang.Class object. All types in Java including the primitive types (int, long, float etc.) and arrays have an associated Class object.
  • 2. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid There are 3 ways to get the instance of Class class. They are as follows: o the .class syntax o getClass() method of Object class o forName() method of Class class 1) The .class syntax: If a type is available but there is no instance then it is possible to obtain a Class by appending ".class" to the name of the type.It can be used for primitive data type also. package com.behsazan; class TestClass {.… } Class aClass = TestClass.class; String className = aClass.getName(); // for primitive Types Class aClass = boolean.class; Class bClass = int.class; String className = aClass.getName(); 2) getClass() method: It should be used if you know the type. TestClass testClassObject =new TestClass(); Class aClass = testClassObject.getClass(); boolean myVar; Class aClass = myVar.getClass(); // compile-time error 3) forName() method: If you don't know the name at compile time, but have the class name as a string at runtime, you can do like this: Class aClass = Class.forName("com.behsazan.TestClass"); Superclass From the Class object you can access the superclass of the class. The superclass class object is a Class object like any other, so you can continue doing class reflection on that too. Here is how: Class superclass = aClass.getSuperclass();
  • 3. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid Constructors You can access the constructors of a class like this: Constructor[] constructors = aClass.getConstructors(); Methods You can access the methods of a class like this: Method[] method = aClass.getMethods(); // get List of methods Method[] method = aClass.getDeclaredMethods(); Method method = aClass.getMethod("methodName", methodParams); Method method = aClass.getDeclaredMethod("methodName", methodParams); getMethod VS getDeclaredMethod: ‫تفاوت‬getMethod‫ﺑا‬getDeclaredMethod‫تاﺑع‬ ‫در‬ ‫كه‬ ‫كه‬ ‫است‬ ‫اين‬ ‫در‬getMethod‫در‬ ‫متد‬ ‫دنبال‬ ‫ﺑه‬ ،‫نكند‬ ‫پيدا‬ ‫را‬ ‫متد‬ ‫جاري‬ ‫كﻼس‬ ‫در‬ ‫اگر‬ ‫كﻼس‬super.‫گردد‬ ‫مي‬ ‫آن‬ Fields You can access the fields (member variables) of a class like this: Field[] fields = aClass.getFields(); Field[] fields = aClass.getDeclaredFields(); Field field = aClass. getField(("fieldName"); Field field = aClass. getDeclaredField(("fieldName"); Package Info You can obtain information about the package from a Class object like this: Class aClass = ... //obtain Class object. See prev. section Package package = aClass.getPackage();
  • 4. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid Modifiers The class modifiers are the keywords "public", "private", "static" etc. The modifiers are packed into an int where each modifier is a flag bit that is either set or cleared. You can obtain the class modifiers like this: Class aClass = ... //obtain Class object int modifiers = aClass.getModifiers(); You can check the modifiers using these methods in the class java.lang.reflect.Modifier: Modifier.isAbstract(int modifiers) Modifier.isFinal(int modifiers) Modifier.isInterface(int modifiers) Modifier.isNative(int modifiers) Modifier.isPrivate(int modifiers) Modifier.isProtected(int modifiers) Modifier.isPublic(int modifiers) Modifier.isStatic(int modifiers) Modifier.isStrict(int modifiers) Modifier.isSynchronized(int modifiers) Modifier.isTransient(int modifiers) Modifier.isVolatile(int modifiers Example: Public class SimpleClass{ public void method1 (){ System.out.println("method1() was called!"); } public void method2 (String tempStr){ System.out.println("method2() was called!" + tempStr); } public void method3 (int tempInt){ System.out.println("method3() was called!" + tempInt);
  • 5. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid } } public static void main(String args[]) { //no paramater Class noparams[] = {}; //String parameter Class[] paramString = new Class[1]; paramString[0] = String.class; //int parameter Class[] paramInt = new Class[1]; paramInt[0] = Integer.TYPE; try { Class tempClass = Class.forName("com.behsazan.SimpleClass"); Object obj = tempClass.newInstance(); //call the method1 method Method method = cls.getDeclaredMethod("method1", noparams); method.invoke(obj, null); //call the method2 with String Inputs Method method = cls.getDeclaredMethod("method2", paramString); method.invoke(obj, new String("inputParams")); //call the method3 with Interger Inputs Method method = cls.getDeclaredMethod("method3", paramInt); method.invoke(obj, 1234); } catch (ClassNotFoundException ee) { System.out.println("Couldn't find class 'SimpleClass'"); System.exit(1); } } TYPE Field for Primitive Type Wrappers The .class syntax is a more convenient and the preferred way to obtain the Class for a primitive type; however there is another way to acquire the Class. Each of the primitive types and void has a wrapper class in java.lang that is used for boxing of primitive types to reference types. Each wrapper class contains a field named TYPE which is equal to the Class for the primitive type being wrapped. Class c = Double.TYPE; is identical to Class c = double.class. Class c = Void.TYPE; is identical to Class c = void.class.
  • 6. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid Reflection – Arrays: Working with arrays via Java Reflection is done using the java.lang.reflect.Array class. Creating Arrays Creating arrays via Java Reflection is done using the java.lang.reflect.Array class. 1. // This code sample creates an array of type int (int.class parameter) and size of 3 int[] intArray = (int[]) Array.newInstance(int.class, 3); 2. int dimensions[] = {3, 4}; int twoDimensionalIntArray[][] = (int[][])Array.newInstance(int.class, dimensions); Accessing Arrays int[] intArray = (int[]) Array.newInstance(int.class, 3); Array.set(intArray, 0, 123); Array.set(intArray, 1, 456); Array.set(intArray, 2, 789); System.out.println("intArray size = " + Array. getLength(intArray)); System.out.println("intArray[0] = " + Array.get(intArray, 0)); System.out.println("intArray[2] = " + Array.get(intArray, 2)); Sample Result: intArray size = 3 intArray[0] = 123 intArray[2] = 789 Obtaining the Class Object of an Array 1. with .class Syntax: Class intArrayClass = int[].class; Class doubleArrayClass = double[].class; Class stringTwoDimensionalArrayClass = String[][].class; 2. Using Class.forName: Class intArray = Class.forName("[I"); // identical to int[].class
  • 7. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid Class cDoubleArray = Class.forName("[D"); // identical to double[].class Class cStringArray = Class.forName("[[Ljava.lang.String;"); // identical to String[][].class Obtaining the Component Type of an Array Once you have obtained the Class object for an array you can access its component type via the Class.getComponentType() method. The component type is the type of the items in the array. For instance, the component type of an int[] array is the int.class Class object. The component type of a String[] array is the java.lang.String Class object. Example1: String[] strings = new String[3]; Class stringArrayClass = strings.getClass(); Class stringArrayComponentType = stringArrayClass.getComponentType(); System.out.println(stringArrayComponentType); // prints : "java.lang.String" Example2: int[] object = {1,2,3}; Class aClass = object.getClass(); if (aClass.isArray()) { Class elementType = aClass.getComponentType(); System.out.println("Array of: " + elementType); // prints : Array of: int } Example3: import java.lang.reflect.Array; public class ReflectionHelloWorld { public static void main(String[] args) { int[] intArray = { 1, 2, 3, 4, 5 }; int[] newIntArray = (int[]) changeArraySize(intArray, 10); print(newIntArray); String[] atr = { "a", "b", "c", "d", "e" }; String[] str1 = (String[]) changeArraySize(atr, 10); print(str1); } // change array size public static Object changeArraySize(Object obj, int len) {
  • 8. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid Class<?> arr = obj.getClass().getComponentType(); Object newArray = Array.newInstance(arr, len); //do array copy int co = Array.getLength(obj); System.arraycopy(obj, 0, newArray, 0, co); return newArray; } // print public static void print(Object obj) { Class<?> c = obj.getClass(); if (!c.isArray()) { return; } System.out.println("nArray length: " + Array.getLength(obj)); for (int i = 0; i < Array.getLength(obj); i++) { System.out.print(Array.get(obj, i) + " "); } } } reflection & Generics: public class MyGenericClass<T extends Number> { private String name = "Default Name"; private int age; private T counter; public MyGenericClass(String tempVar) { this.name = tempVar; } public String getName() { return name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public T getCounter() { return counter; } public void setCounter(T counter) {
  • 9. Hamid Ghorbani Java Advanced Tutorial(Reflection) https://ir.linkedin.com/in/ghorbanihamid this.counter = counter; } public < E > void printArray(E[] inputArray ) { for(E element : inputArray) { System.out.printf("%s ", element); } System.out.println(""); } } public static void main(String[] args) { try { Class<?> aClass = Class.forName("MyGenericClass"); Constructor constructorMethod = aClass.getConstructor(String.class); Object myGenericClassObj = constructorMethod.newInstance("This is Reflection Test."); Method getMyVarMethod = myGenericClassObj.getClass().getMethod("getName", null); System.out.println(getMyVarMethod.invoke(myGenericClassObj)); Method setAgeMethod = myGenericClassObj.getClass().getMethod("setAge", Integer.TYPE); setAgeMethod.invoke(myGenericClassObj,38); Method getAgeMethod = myGenericClassObj.getClass().getMethod("getAge", null); Object returnObj = getAgeMethod.invoke(myGenericClassObj); System.out.println("The age is : " + returnObj.toString()); Method setCounterMethod = myGenericClassObj.getClass().getMethod("setCounter", Number.class); setCounterMethod.invoke(myGenericClassObj,1000); Method getCounterMethod = myGenericClassObj.getClass().getMethod("getCounter", null); returnObj = getCounterMethod.invoke(myGenericClassObj); System.out.println("Counter is : " + returnObj.toString()); Method printArrMethod = myGenericClassObj.getClass().getMethod("printArray", Object[].class); Object[] nums = {1,2,3}; String[] strs = { "str1", "str2"}; Object[] objs = {10, "a", 20 , "b",30, "c"}; printArrMethod.invoke(myGenericClassObj,new Object[]{ nums }); printArrMethod.invoke(myGenericClassObj,new Object[]{ strs }); printArrMethod.invoke(myGenericClassObj,new Object[]{ objs }); } catch (Exception e){ System.out.print(e.getMessage()); } }