[go: up one dir, main page]

0% found this document useful (0 votes)
57 views13 pages

Reflections in Java

Reflection in Java allows examining and manipulating code at runtime. This includes getting information about classes, fields, methods, and more. Some common uses of reflection include IDE autocompletion, ORM frameworks, and dependency injection in Spring. However, reflection also has performance and security drawbacks due to its runtime nature. The core reflection API classes in Java include Class, Field, Method, Constructor, and Array.

Uploaded by

alizafar9892
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views13 pages

Reflections in Java

Reflection in Java allows examining and manipulating code at runtime. This includes getting information about classes, fields, methods, and more. Some common uses of reflection include IDE autocompletion, ORM frameworks, and dependency injection in Spring. However, reflection also has performance and security drawbacks due to its runtime nature. The core reflection API classes in Java include Class, Field, Method, Constructor, and Array.

Uploaded by

alizafar9892
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 13

Reflection in Java

-----------------------------------------
Ability of computer program to examine, introspect its own behaviour at runtime
applications running in java virtual machine.
-----------------------------------------
Use of Reflection
-----------------------------------------
Using Reflection in Java we can inspect a class and get information about the
fields, methods, constructors, implemented interfaces, superclasses at run time.
Using reflection, we can access a private field and invoke a private method from
another class.
-----------------------------------------
Where is reflection API used
-----------------------------------------
You may not have a need to use reflection API in your application but you would
have seen its usage in many tools or applications you are using.
1. The IDE like Eclipse giving you the list of methods in a class, auto completing
the field or method name.
2. Your persistance framework matching the fields in your objects with fields in
the database table at runtime.
3. JUnit getting the information about the methods to be invoked.
4. Spring framework getting the class information using the bean definition and
also getting the setters and gertters or constructors of the class. So, you can say
Dependency Injection in Spring depends heavily on reflection.
-----------------------------------------
Drawbacks of reflection in java
-----------------------------------------
Performance Overhead(Since it should have access to runtime)
Security Restrictions
Against Object oriented principles(Breaks abstraction)
-----------------------------------------
Reflection API in java
-----------------------------------------
-> Class(java.lang.Class)
For every type of object, JVM instantiates an immutable instance of java which
provides methods to examine the runtime properties of object including its members
and type information. Class also provides a new ability to create objects, most
importantly it is the entry point for all the reflection API.

->Member(java.lang.reflect.Member)
This is an interface.

-Field(java.lang.reflect.Field)
Field class provides methods for type information for setting and getting fields
for the given object.

->Method(java.lang.reflect.Method)
Method class provides methods for obtaining type information for the parameters and
return types. It may also be used to invoke methods on the given object.

->Constructor(java.lang.reflect.Constructor)
Constructor class provides methods for obtaining the information about constructor
of the class. If we reflectively invoke the constructor, a new instance of the
given class will be created.

->Array(java.lang.reflect.Array)
The array class provides static methods to create dynamically and access java
arrays.
-----------------------------------------
Reflection Example code
-----------------------------------------
Person.class
package com.infotech.model;

public class Person {

private String name;


private Integer age;

public Person(String name, Integer age) {


super();
this.name = name;
this.age = age;
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public Integer getAge() {


return age;
}

public void setAge(Integer age) {


this.age = age;
}

Test.class
package com.infotech.client;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Test {

public static void main(String[] args) {

try {
Class<?> c = Class.forName("com.infotech.model.Person");

// 1. Getting constructors of the class


System.out.println("------------------------------- 1. Getting
constructors of the class");
Constructor<?>[] constructors = c.getConstructors();
System.out.println("Costructors: "
+Arrays.toString(constructors));

// 2. Getting all methods(even inherited) of the class


System.out.println("-------------------------------2. Getting all
methods(even inherited) of the class");
Method[] methods = c.getMethods();
System.out.println("Methods: " + Arrays.toString(methods));

// 3. Getting methods of the class


System.out.println("-------------------------------3. Getting
methods of the class");
Method[] declaredMethods = c.getDeclaredMethods();
System.out.println("Declared Methods: " +
Arrays.toString(declaredMethods));

// 4. Getting fields of the class


System.out.println("-------------------------------4. Getting
fields of the class");
Field[] fields = c.getDeclaredFields();
System.out.println("Fields: " +Arrays.toString(fields));

} catch(ClassNotFoundException e) {
e.printStackTrace();
}

}
-----------------------------------------
Getting the metadata about the class using Reflection API
-----------------------------------------
IntTest.class
package com.infotech.model;

public interface IntTest {


public abstract void showValue();
}

Parent.class
package com.infotech.model;

public class Parent {

private String name;

public Parent(String name) {


super();
this.name = name;
}

public void displayName() {


System.out.println(name);
}

public String getName() {


return name;
}

}
ChildClass.class
package com.infotech.model;

//@Deprecated
public class ChildClass extends Parent implements IntTest {

private int value;

public ChildClass(String name,int value) {


super(name);
this.value=value;
}

@Override
public void showValue() {
System.out.println("Value:" +value);
}

ReflectionTest.class
package com.infotech.client;

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;

public class ReflectionTest {

public static void main(String[] args) {

//1. To get the class name

System.out.println("-------------------------------1.To get the class


name.----------------------");
Class<?> c1;

try {
c1 = Class.forName("com.infotech.model.ChildClass");
System.out.println("Class name : " + c1.getName());
System.out.println("Class name : " + c1.getSimpleName());
}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//2. Getting super class using reflection

System.out.println("-------------------------------2. Getting super


class using reflection----------------------");
Class<?> c2;

try {
c2 = Class.forName("com.infotech.model.ChildClass");
System.out.println("Super Class name : " + c2.getSuperclass());
}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//3. Getting implemented or extended interfaces using reflection

System.out.println("-------------------------------3. Getting
implemented or extended interfaces using reflection----------------------");
Class<?> c3;

try {
c3 = Class.forName("com.infotech.model.ChildClass");
System.out.println("Interface : " +
Arrays.toString(c3.getInterfaces()));
}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//4. Getting class modifiers using reflection

System.out.println("-------------------------------4.
Getting class modifiers using reflection----------------------");
Class<?> c4;

try {
c4 = Class.forName("com.infotech.model.ChildClass");
int modifiers = c4.getModifiers();
System.out.println("Modifiers : " +
Modifier.toString(modifiers));
}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//5. Getting fields of the class using reflection

System.out.println("-------------------------------5.
Getting fields of the class using reflection----------------------");
Class<?> c5;

try {
c5 = Class.forName("com.infotech.model.ChildClass");
//getting fields of the class
Field[] fields = c5.getFields();
System.out.println("All accessible Fields(public) : "
+ Arrays.toString(fields));

//getting fields of the class


Field[] field = c5.getDeclaredFields();
System.out.println("Fields : " +
Arrays.toString(field));

}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//6. Getting constructors of the class using reflection


System.out.println("-------------------------------6.
Getting constructors of the class using reflection----------------------");
Class<?> c6;

try {
c6 = Class.forName("com.infotech.model.ChildClass");
//getting fields of the class
Constructor<?>[] constructors = c6.getConstructors();
System.out.println("All accessible
constructors(public) : " + Arrays.toString(constructors));

//getting fields of the class


Constructor<?>[] deconstructors =
c6.getDeclaredConstructors();
System.out.println("All constructors : " +
Arrays.toString(deconstructors));

}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//7. Getting methods of the class using reflection

System.out.println("-------------------------------7.
Getting methods of the class using reflection----------------------");
Class<?> c7;

try {
c7 = Class.forName("com.infotech.model.ChildClass");
//getting fields of the class
Method[] methods = c7.getMethods();
System.out.println("All accessible methods including
parent : " + Arrays.toString(methods));

//getting fields of the class


methods = c7.getDeclaredMethods();
System.out.println("All methods : " +
Arrays.toString(methods));

}catch(ClassNotFoundException e) {
e.printStackTrace();
}

//8. Getting annotations of the class using reflection

System.out.println("------------------------------8.
Getting annotations of the class using reflection----------------------");
Class<?> c8;

try {
c8 = Class.forName("com.infotech.model.ChildClass");
//getting fields of the class
Annotation[] annotations = c8.getAnnotations();
System.out.println("All accessible annotations
including parent : " + Arrays.toString(annotations));

//getting fields of the class


annotations = c8.getDeclaredAnnotations();
System.out.println("All Annotations : " +
Arrays.toString(annotations));

}catch(ClassNotFoundException e) {
e.printStackTrace();
}

}
-----------------------------------------
Invoking private method of the class from another class using reflection in java
-----------------------------------------
Welcome.class
package com.infotech.model;

public class Welcome {

private String greet(String name) {


if(name==null || name.isEmpty()) {
return "Hello Stranger";
}

return "Hello, " + name;

}
}

ReflectionTest.class
package com.infotech.client;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.infotech.model.Welcome;

public class ReflectionTest {

public static void main(String[] args) {

try {
Class<?> cls = Class.forName("com.infotech.model.Welcome");
Method method = cls.getDeclaredMethod("greet", String.class);
method.setAccessible(true);

Object object = method.invoke(new Welcome(), "KK");


String result = (String) object;
System.out.println(result);
} catch (ClassNotFoundException | NoSuchMethodException |
IllegalAccessException
| InvocationTargetException e) {
e.printStackTrace();
}
}

}
-----------------------------------------
Access private variables from another class in java
-----------------------------------------
Welcome.class
package com.infotech.model;

public class Welcome {

private String message = "Hello";


}

ReflectionTest.class
package com.infotech.client;

import java.lang.reflect.Field;

import com.infotech.model.Welcome;

public class ReflectionTest {

public static void main(String[] args) {


try {
Class<?> cls = Class.forName("com.infotech.model.Welcome");
Field field = cls.getDeclaredField("message");
field.setAccessible(true);
Object object = field.get(new Welcome());
String result = (String) object;
System.out.println(result);
} catch (ClassNotFoundException | IllegalAccessException |
NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}

-----------------------------------------
Creating class instance using reflection
-----------------------------------------
Using Constructor clas in java, we can get information about the modifiers,
parameters, annotations and thrown exceptions. You can also create a new instance
of a class using a specified constructor.

getConstructor(Class<?>... parameterTypes)
getConstructors()
getDeclaredConstructor(Class<?>... parameterTypes)
getDeclaredConstructors()

TestClass.class
package com.infotech.model;

public class TestClass {

private int value;


private String name;

public TestClass(int value, String name) {


this.value = value;
this.name = name;
}
//private constructor
private TestClass() {

public void showValue() {


System.out.println("Name: " + name +"\t" + "Value :" + value);
}

ReflectConstructorTest.class
package com.infotech.client;

import java.lang.reflect.Constructor;
import java.util.Arrays;

public class ReflectConstructorTest {

public static void main(String[] args) {

try {
Class<?> cls = Class.forName("com.infotech.model.TestClass");

//1.To get constructor with 2 args


System.out.println("---------------1.To get constructor with 2
args------------------");
Constructor<?> constructor = cls.getConstructor(int.class,
String.class);
System.out.println("Constructor :" + constructor.toString());

//2.Getting constructors of the class


System.out.println("---------------2.Getting constructos of the
class------------------");
Constructor<?>[] constructors = cls.getConstructors();
System.out.println("Constructors :" +
Arrays.toString(constructors));

//3.To get private constructors using getDeclaredConstructor()


method
System.out.println("---------------3.To get private constructors
using getDeclaredConstructor() method------------------");
constructor = cls.getDeclaredConstructor();
System.out.println("Constructor :" + constructor.toString());

//4.To get all public private protected default constructors


using getDeclaredConstructor() method
System.out.println("---------------4.To get all public private
protected default constructors using getDeclaredConstructor()
method------------------");
constructors = cls.getDeclaredConstructors();
System.out.println("Constructors :" +
Arrays.toString(constructors));

} catch (ClassNotFoundException |NoSuchMethodException e) {


e.printStackTrace();
}
}

There are 2 methods in Reflection API for creating instances of classes.


-> java.lang.reflect.Constructor.newInstance()
-> Class.newInstance().
It is preferable to go with the one provided by the constructor class for the below
reasons.
1. Class.newIstance() can only invoke the 0-argument constructor
while Constructor.newInstance() may invoke any constructor, regardles of the
number of parameters.
2. Class.newInstance() requires that the constructor be visible.
Constructor.newInstance() can invoke private constructgors also by setting
accessibility to true.
3. Class.newInstance() throws any exception thrown by the constructor whether it is
checked or unchecked exception.Constructor.newInstance() always wraps the thrown
exception with an InvocagtionTargetException.

TestClass.class
package com.infotech.model;

public class TestClass {


private int value;
private String name;

public TestClass(int value, String name) {


this.value = value;
this.name = name;
}

// private constructor
private TestClass() {

public void showValue() {


System.out.println("Name: " + name + "\t" + "Value :" + value);
}
}

ReflectionTest.class
package com.infotech.Client;

import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;

import com.infotech.model.TestClass;

public class ReflectionTest {

public static void main(String[] args) {


Class<?> cls;

try {
cls = Class.forName("com.infotech.model.TestClass");
Constructor<?>[] cons = cls.getDeclaredConstructors();
for (Constructor<?> con : cons) {
System.out.println("Constructor :" + con.getName());
try {
TestClass testClass;

if(Modifier.toString(con.getModifiers()).equals("private")) {
//Setting accessibility as true
con.setAccessible(true);
testClass = (TestClass)con.newInstance();
} else {
testClass = (TestClass) con.newInstance(200,
"ConstructorTest");
}
testClass.showValue();
}catch (Exception e) {
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}

-----------------------------------------
Identify array using reflection and creating new array using reflection
-----------------------------------------
Person.class
package com.infotech.model;

public class Person {

private int age;


private long[] phoneNumber;

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

public long[] getPhoneNumber() {


return phoneNumber;
}

public void setPhoneNumber(long[] phoneNumber) {


this.phoneNumber = phoneNumber;
}

IdentifyArrayUsingReflectionTest.class
package com.infotech.client;

import java.lang.reflect.Field;
public class IdentifyArrayUsingReflectionTest {

public static void main(String[] args) {

try {
Class<?> cls = Class.forName("com.infotech.model.Person");
Field[] fields = cls.getDeclaredFields();
for (Field f : fields) {
Class<?> type = f.getType();

//checking for array


if(type.isArray()) {
System.out.println("Array Found :" + f.getName());
}
}
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}

GetAndSetArrayUsingReflectionTest.class
package com.infotech.client;

import java.lang.reflect.Array;

public class GetAndSetArrayUsingReflectionTest {

public static void main(String[] args) {

double[] doubleArray = (double[]) Array.newInstance(double.class, 5);


System.out.println("Length of the array : " + doubleArray.length);

//Setting values using setDouble and set methods


System.out.println("----------------Setting values using setDouble and
set methods------------------");
Array.setDouble(doubleArray, 0, 15.0);
Array.set(doubleArray, 1, 29.0);
Array.setDouble(doubleArray, 2, 45.0);

//Getting values using setDouble and set methods


System.out.println("----------------Getting values using setDouble and
set methods------------------");
System.out.println(Array.get(doubleArray, 0));
System.out.println(Array.getDouble(doubleArray, 1));
System.out.println(Array.getDouble(doubleArray, 2));
System.out.println(Array.getDouble(doubleArray, 3));

-----------------------------------------
Generating Getter and Setters method in java
-----------------------------------------

You might also like