SlideShare a Scribd company logo
1 of 9
Download to read offline
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

Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 
Java multi threading and synchronization
Java multi threading and synchronizationJava multi threading and synchronization
Java multi threading and synchronizationrithustutorials
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Javabackdoor
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satyaSatya Johnny
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHPLorna Mitchell
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick ReferenceFrescatiStory
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+javaYe Win
 
201 core java interview questions oo ps interview questions - javatpoint
201 core java interview questions   oo ps interview questions - javatpoint201 core java interview questions   oo ps interview questions - javatpoint
201 core java interview questions oo ps interview questions - javatpointravi tyagi
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat SheetGlowTouch
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...Sagar Verma
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfacesDevaKumari Vijay
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceOUM SAOKOSAL
 

What's hot (20)

Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Java multi threading and synchronization
Java multi threading and synchronizationJava multi threading and synchronization
Java multi threading and synchronization
 
Object and Classes in Java
Object and Classes in JavaObject and Classes in Java
Object and Classes in Java
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
Advance java kvr -satya
Advance java  kvr -satyaAdvance java  kvr -satya
Advance java kvr -satya
 
Object Oriented Programming in PHP
Object Oriented Programming in PHPObject Oriented Programming in PHP
Object Oriented Programming in PHP
 
02 basic java programming and operators
02 basic java programming and operators02 basic java programming and operators
02 basic java programming and operators
 
Java Programming Guide Quick Reference
Java Programming Guide Quick ReferenceJava Programming Guide Quick Reference
Java Programming Guide Quick Reference
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
Object+oriented+programming+in+java
Object+oriented+programming+in+javaObject+oriented+programming+in+java
Object+oriented+programming+in+java
 
201 core java interview questions oo ps interview questions - javatpoint
201 core java interview questions   oo ps interview questions - javatpoint201 core java interview questions   oo ps interview questions - javatpoint
201 core java interview questions oo ps interview questions - javatpoint
 
Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
OOPS in java | Super and this Keyword | Memory Management in java | pacakages...
 
Unit3 part3-packages and interfaces
Unit3 part3-packages and interfacesUnit3 part3-packages and interfaces
Unit3 part3-packages and interfaces
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Java OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - InheritanceJava OOP Programming language (Part 5) - Inheritance
Java OOP Programming language (Part 5) - Inheritance
 

Similar to Java Reflection

Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxPoonam60376
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 InheritanceOUM SAOKOSAL
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAVINASH KUMAR
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slotsmha4
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorialrajkamaltibacademy
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxchetanpatilcp783
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Sagar Verma
 
Class loader basic
Class loader basicClass loader basic
Class loader basic명철 강
 
Object Oriented Programming in Android Studio
Object Oriented Programming in Android StudioObject Oriented Programming in Android Studio
Object Oriented Programming in Android StudioMahmoodGhaemMaghami
 

Similar to Java Reflection (20)

Java Reflection Concept and Working
Java Reflection Concept and WorkingJava Reflection Concept and Working
Java Reflection Concept and Working
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
Introduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptxIntroduction of Object Oriented Programming Language using Java. .pptx
Introduction of Object Oriented Programming Language using Java. .pptx
 
Chapter 8 Inheritance
Chapter 8 InheritanceChapter 8 Inheritance
Chapter 8 Inheritance
 
inheritance.pptx
inheritance.pptxinheritance.pptx
inheritance.pptx
 
19 reflection
19   reflection19   reflection
19 reflection
 
Advanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sirAdvanced java jee material by KV Rao sir
Advanced java jee material by KV Rao sir
 
Reflection
ReflectionReflection
Reflection
 
Adv kvr -satya
Adv  kvr -satyaAdv  kvr -satya
Adv kvr -satya
 
Java Reflection
Java ReflectionJava Reflection
Java Reflection
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots03 object-classes-pbl-4-slots
03 object-classes-pbl-4-slots
 
Java scjp-part1
Java scjp-part1Java scjp-part1
Java scjp-part1
 
Corejava Training in Bangalore Tutorial
Corejava Training in Bangalore TutorialCorejava Training in Bangalore Tutorial
Corejava Training in Bangalore Tutorial
 
Sonu wiziq
Sonu wiziqSonu wiziq
Sonu wiziq
 
Chap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptxChap-2 Classes & Methods.pptx
Chap-2 Classes & Methods.pptx
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Class loader basic
Class loader basicClass loader basic
Class loader basic
 
UNIT 5.pptx
UNIT 5.pptxUNIT 5.pptx
UNIT 5.pptx
 
Object Oriented Programming in Android Studio
Object Oriented Programming in Android StudioObject Oriented Programming in Android Studio
Object Oriented Programming in Android Studio
 

More from Hamid Ghorbani

More from Hamid Ghorbani (13)

Spring aop
Spring aopSpring aop
Spring aop
 
Spring boot jpa
Spring boot jpaSpring boot jpa
Spring boot jpa
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Payment Tokenization
Payment TokenizationPayment Tokenization
Payment Tokenization
 
Reactjs Basics
Reactjs BasicsReactjs Basics
Reactjs Basics
 
Rest web service
Rest web serviceRest web service
Rest web service
 
Java I/o streams
Java I/o streamsJava I/o streams
Java I/o streams
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java collections
Java collectionsJava collections
Java collections
 
IBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) FundamentalsIBM Integeration Bus(IIB) Fundamentals
IBM Integeration Bus(IIB) Fundamentals
 
ESB Overview
ESB OverviewESB Overview
ESB Overview
 
Spring security configuration
Spring security configurationSpring security configuration
Spring security configuration
 
SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)SOA & ESB in banking systems(Persian language)
SOA & ESB in banking systems(Persian language)
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noidabntitsolutionsrishis
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in NoidaBuds n Tech IT Solutions: Top-Notch Web Services in Noida
Buds n Tech IT Solutions: Top-Notch Web Services in Noida
 

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()); } }