SlideShare uma empresa Scribd logo
1 de 9
Baixar para ler 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());
}
}

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Semelhante a 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
 

Semelhante a 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
 

Mais de Hamid Ghorbani

Mais de 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)
 

Último

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
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.pdfkalichargn70th171
 
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-...Steffen Staab
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
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 serviceanilsa9823
 
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 PrecisionSolGuruz
 
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.pdfWave PLM
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
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
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
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 🔝✔️✔️Delhi Call girls
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
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 Modelsaagamshah0812
 
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.pdfkalichargn70th171
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 

Último (20)

TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
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
 
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-...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
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
 
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
 
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
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
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 ☂️
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
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
 
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 🔝✔️✔️
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
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
 
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
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 

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