[Go to site: main page, start]

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

Java Reflection API Overview

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)
10 views13 pages

Java Reflection API Overview

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

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([Link])
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([Link])
This is an interface.

-Field([Link])
Field class provides methods for type information for setting and getting fields
for the given object.

->Method([Link])
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([Link])
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([Link])
The array class provides static methods to create dynamically and access java
arrays.
-----------------------------------------
Reflection Example code
-----------------------------------------
[Link]
package [Link];

public class Person {

private String name;


private Integer age;

public Person(String name, Integer age) {


super();
[Link] = name;
[Link] = age;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public Integer getAge() {


return age;
}

public void setAge(Integer age) {


[Link] = age;
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];

public class Test {

public static void main(String[] args) {

try {
Class<?> c = [Link]("[Link]");

// 1. Getting constructors of the class


[Link]("------------------------------- 1. Getting
constructors of the class");
Constructor<?>[] constructors = [Link]();
[Link]("Costructors: "
+[Link](constructors));

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


[Link]("-------------------------------2. Getting all
methods(even inherited) of the class");
Method[] methods = [Link]();
[Link]("Methods: " + [Link](methods));

// 3. Getting methods of the class


[Link]("-------------------------------3. Getting
methods of the class");
Method[] declaredMethods = [Link]();
[Link]("Declared Methods: " +
[Link](declaredMethods));

// 4. Getting fields of the class


[Link]("-------------------------------4. Getting
fields of the class");
Field[] fields = [Link]();
[Link]("Fields: " +[Link](fields));

} catch(ClassNotFoundException e) {
[Link]();
}

}
-----------------------------------------
Getting the metadata about the class using Reflection API
-----------------------------------------
[Link]
package [Link];

public interface IntTest {


public abstract void showValue();
}

[Link]
package [Link];

public class Parent {

private String name;

public Parent(String name) {


super();
[Link] = name;
}

public void displayName() {


[Link](name);
}

public String getName() {


return name;
}

}
[Link]
package [Link];

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

private int value;

public ChildClass(String name,int value) {


super(name);
[Link]=value;
}

@Override
public void showValue() {
[Link]("Value:" +value);
}

[Link]
package [Link];

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class ReflectionTest {

public static void main(String[] args) {

//1. To get the class name

[Link]("-------------------------------[Link] get the class


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

try {
c1 = [Link]("[Link]");
[Link]("Class name : " + [Link]());
[Link]("Class name : " + [Link]());
}catch(ClassNotFoundException e) {
[Link]();
}

//2. Getting super class using reflection

[Link]("-------------------------------2. Getting super


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

try {
c2 = [Link]("[Link]");
[Link]("Super Class name : " + [Link]());
}catch(ClassNotFoundException e) {
[Link]();
}

//3. Getting implemented or extended interfaces using reflection

[Link]("-------------------------------3. Getting
implemented or extended interfaces using reflection----------------------");
Class<?> c3;

try {
c3 = [Link]("[Link]");
[Link]("Interface : " +
[Link]([Link]()));
}catch(ClassNotFoundException e) {
[Link]();
}

//4. Getting class modifiers using reflection

[Link]("-------------------------------4.
Getting class modifiers using reflection----------------------");
Class<?> c4;

try {
c4 = [Link]("[Link]");
int modifiers = [Link]();
[Link]("Modifiers : " +
[Link](modifiers));
}catch(ClassNotFoundException e) {
[Link]();
}

//5. Getting fields of the class using reflection

[Link]("-------------------------------5.
Getting fields of the class using reflection----------------------");
Class<?> c5;

try {
c5 = [Link]("[Link]");
//getting fields of the class
Field[] fields = [Link]();
[Link]("All accessible Fields(public) : "
+ [Link](fields));

//getting fields of the class


Field[] field = [Link]();
[Link]("Fields : " +
[Link](field));

}catch(ClassNotFoundException e) {
[Link]();
}

//6. Getting constructors of the class using reflection


[Link]("-------------------------------6.
Getting constructors of the class using reflection----------------------");
Class<?> c6;

try {
c6 = [Link]("[Link]");
//getting fields of the class
Constructor<?>[] constructors = [Link]();
[Link]("All accessible
constructors(public) : " + [Link](constructors));

//getting fields of the class


Constructor<?>[] deconstructors =
[Link]();
[Link]("All constructors : " +
[Link](deconstructors));

}catch(ClassNotFoundException e) {
[Link]();
}

//7. Getting methods of the class using reflection

[Link]("-------------------------------7.
Getting methods of the class using reflection----------------------");
Class<?> c7;

try {
c7 = [Link]("[Link]");
//getting fields of the class
Method[] methods = [Link]();
[Link]("All accessible methods including
parent : " + [Link](methods));

//getting fields of the class


methods = [Link]();
[Link]("All methods : " +
[Link](methods));

}catch(ClassNotFoundException e) {
[Link]();
}

//8. Getting annotations of the class using reflection

[Link]("------------------------------8.
Getting annotations of the class using reflection----------------------");
Class<?> c8;

try {
c8 = [Link]("[Link]");
//getting fields of the class
Annotation[] annotations = [Link]();
[Link]("All accessible annotations
including parent : " + [Link](annotations));

//getting fields of the class


annotations = [Link]();
[Link]("All Annotations : " +
[Link](annotations));

}catch(ClassNotFoundException e) {
[Link]();
}

}
-----------------------------------------
Invoking private method of the class from another class using reflection in java
-----------------------------------------
[Link]
package [Link];

public class Welcome {

private String greet(String name) {


if(name==null || [Link]()) {
return "Hello Stranger";
}

return "Hello, " + name;

}
}

[Link]
package [Link];

import [Link];
import [Link];

import [Link];

public class ReflectionTest {

public static void main(String[] args) {

try {
Class<?> cls = [Link]("[Link]");
Method method = [Link]("greet", [Link]);
[Link](true);

Object object = [Link](new Welcome(), "KK");


String result = (String) object;
[Link](result);
} catch (ClassNotFoundException | NoSuchMethodException |
IllegalAccessException
| InvocationTargetException e) {
[Link]();
}
}

}
-----------------------------------------
Access private variables from another class in java
-----------------------------------------
[Link]
package [Link];

public class Welcome {

private String message = "Hello";


}

[Link]
package [Link];

import [Link];

import [Link];

public class ReflectionTest {

public static void main(String[] args) {


try {
Class<?> cls = [Link]("[Link]");
Field field = [Link]("message");
[Link](true);
Object object = [Link](new Welcome());
String result = (String) object;
[Link](result);
} catch (ClassNotFoundException | IllegalAccessException |
NoSuchFieldException | SecurityException e) {
[Link]();
}

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

[Link]
package [Link];

public class TestClass {

private int value;


private String name;

public TestClass(int value, String name) {


[Link] = value;
[Link] = name;
}
//private constructor
private TestClass() {

public void showValue() {


[Link]("Name: " + name +"\t" + "Value :" + value);
}

[Link]
package [Link];

import [Link];
import [Link];

public class ReflectConstructorTest {

public static void main(String[] args) {

try {
Class<?> cls = [Link]("[Link]");

//[Link] get constructor with 2 args


[Link]("---------------[Link] get constructor with 2
args------------------");
Constructor<?> constructor = [Link]([Link],
[Link]);
[Link]("Constructor :" + [Link]());

//[Link] constructors of the class


[Link]("---------------[Link] constructos of the
class------------------");
Constructor<?>[] constructors = [Link]();
[Link]("Constructors :" +
[Link](constructors));

//[Link] get private constructors using getDeclaredConstructor()


method
[Link]("---------------[Link] get private constructors
using getDeclaredConstructor() method------------------");
constructor = [Link]();
[Link]("Constructor :" + [Link]());

//[Link] get all public private protected default constructors


using getDeclaredConstructor() method
[Link]("---------------[Link] get all public private
protected default constructors using getDeclaredConstructor()
method------------------");
constructors = [Link]();
[Link]("Constructors :" +
[Link](constructors));

} catch (ClassNotFoundException |NoSuchMethodException e) {


[Link]();
}
}

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


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

[Link]
package [Link];

public class TestClass {


private int value;
private String name;

public TestClass(int value, String name) {


[Link] = value;
[Link] = name;
}

// private constructor
private TestClass() {

public void showValue() {


[Link]("Name: " + name + "\t" + "Value :" + value);
}
}

[Link]
package [Link];

import [Link];
import [Link];

import [Link];

public class ReflectionTest {

public static void main(String[] args) {


Class<?> cls;

try {
cls = [Link]("[Link]");
Constructor<?>[] cons = [Link]();
for (Constructor<?> con : cons) {
[Link]("Constructor :" + [Link]());
try {
TestClass testClass;

if([Link]([Link]()).equals("private")) {
//Setting accessibility as true
[Link](true);
testClass = (TestClass)[Link]();
} else {
testClass = (TestClass) [Link](200,
"ConstructorTest");
}
[Link]();
}catch (Exception e) {
}
}
} catch (ClassNotFoundException e) {
[Link]();
}

-----------------------------------------
Identify array using reflection and creating new array using reflection
-----------------------------------------
[Link]
package [Link];

public class Person {

private int age;


private long[] phoneNumber;

public int getAge() {


return age;
}

public void setAge(int age) {


[Link] = age;
}

public long[] getPhoneNumber() {


return phoneNumber;
}

public void setPhoneNumber(long[] phoneNumber) {


[Link] = phoneNumber;
}

[Link]
package [Link];

import [Link];
public class IdentifyArrayUsingReflectionTest {

public static void main(String[] args) {

try {
Class<?> cls = [Link]("[Link]");
Field[] fields = [Link]();
for (Field f : fields) {
Class<?> type = [Link]();

//checking for array


if([Link]()) {
[Link]("Array Found :" + [Link]());
}
}
}catch (ClassNotFoundException e) {
[Link]();
}
}

[Link]
package [Link];

import [Link];

public class GetAndSetArrayUsingReflectionTest {

public static void main(String[] args) {

double[] doubleArray = (double[]) [Link]([Link], 5);


[Link]("Length of the array : " + [Link]);

//Setting values using setDouble and set methods


[Link]("----------------Setting values using setDouble and
set methods------------------");
[Link](doubleArray, 0, 15.0);
[Link](doubleArray, 1, 29.0);
[Link](doubleArray, 2, 45.0);

//Getting values using setDouble and set methods


[Link]("----------------Getting values using setDouble and
set methods------------------");
[Link]([Link](doubleArray, 0));
[Link]([Link](doubleArray, 1));
[Link]([Link](doubleArray, 2));
[Link]([Link](doubleArray, 3));

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

Common questions

Powered by AI

Using the Java reflection API, all fields of a class can be obtained and printed by utilizing methods such as `getFields()` for accessible public fields and `getDeclaredFields()` for all fields regardless of their visibility. `getDeclaredFields()` is particularly effective in accessing private, protected, or default access fields. By setting these fields to be accessible using `field.setAccessible(true)`, their values can be retrieved and printed even if they are not public. This comprehensive field introspection is useful for tools and frameworks that need to deeply interact with object data beyond the provided public interfaces .

Creating a new instance of a class using reflection involves first fetching the appropriate constructor with `getConstructor()` or `getDeclaredConstructor()`. If the constructor is private, `setAccessible(true)` must be invoked to bypass access control checks. The constructor can then be called with `newInstance()`, passing any required parameters. During this process, several checks occur: validation of parameter types to match the constructor's formal parameters and accessibility checks for non-public constructors. Yet, the accessibility can be overridden. This reflective instantiation is wrapped in `InvocationTargetException` if exceptions are thrown, requiring additional handling. This elaborate process demands meticulous checking of types, access levels, and exception management to avoid runtime errors .

In frameworks like Spring, reflection plays a crucial role in implementing features such as dependency injection. Through reflection, Spring can introspect classes defined as beans to obtain metadata about fields, constructors, and methods (including private ones) to manage object creation and dependency resolution dynamically. This allows Spring to inject dependencies at runtime based on the configuration without requiring explicit constructor or method calls, thereby making the system more flexible and less dependent on compile-time configurations. Reflection thus provides the underlying mechanism for Spring's capability to dynamically wire dependencies and manage the application context .

The main drawbacks of using reflection in Java include performance overhead since additional processing is required at runtime, potential security vulnerabilities due to its ability to access private data, and violation of object-oriented principles, such as encapsulation, as it allows access to and modification of private members. Despite these drawbacks, reflection remains valuable because it provides capabilities critical for building dynamic frameworks and libraries that require runtime inspection and manipulation, such as dependency injection in Spring or unit testing frameworks like JUnit .

Reflection in Java allows programs to examine and interact with their structure at runtime. By using reflection, developers can inspect classes and retrieve information about fields, methods, constructors, implemented interfaces, and superclasses of classes loaded into the JVM. This capability is utilized in Integrated Development Environments (IDEs) like Eclipse for features such as code autocompletion, in persistence frameworks for matching object fields with database tables, and in frameworks like Spring for dependency injection via introspection of class definitions and methods .

Reflection can be used to invoke a private method in Java by first retrieving the method from the class using `getDeclaredMethod`, then making the method accessible using `setAccessible(true)`, and finally invoking it using `invoke`. For example, using reflection, the private method `greet` from the `Welcome` class can be invoked with a required argument. This ability poses security risks as it breaks encapsulation, potentially allowing unauthorized access to modify or retrieve sensitive data or logic not intended to be exposed .

The reflection API can be misused in a manner that allows access to and modification of classes' private fields and methods, thereby violating object-oriented principles such as encapsulation. Reflection permits the exposure of implementation details that should remain internal to the class, leading to situations where class abstractions are disregarded. For instance, altering internal data without going through the class's defined interface can lead to instability and unpredictable behavior. Additionally, reflection might breach modularity and security constraints, potentially resulting in unauthorized access to sensitive parts of code, hence making the system more error-prone and less secure .

Java reflection facilitates obtaining a class's metadata at runtime. Using `Class.forName()`, a specific class can be loaded and inspected. The class name can be retrieved via `getName()` and `getSimpleName()`, while its superclass is obtained using `getSuperclass()`. Interfaces implemented by the class are accessible through `getInterfaces()`, and the class modifiers (like public, private) can be determined using `getModifiers()` combined with `Modifier.toString()`. This introspective ability is crucial for dynamic type inspection and manipulation, which is extensively used in frameworks and tools that require runtime adaptability and configuration .

The `Constructor.newInstance()` method is preferred over `Class.newInstance()` because the former can invoke any constructor regardless of its parameter list, while `Class.newInstance()` is limited to only zero-argument constructors. Additionally, `Constructor.newInstance()` can invoke private constructors by changing their accessibility, whereas `Class.newInstance()` requires constructors to be public. Furthermore, exceptions thrown by constructors in `Constructor.newInstance()` are wrapped in `InvocationTargetException`, which provides more context for exception handling .

By using the Java reflection API, arrays can be handled and manipulated at runtime by leveraging the `Array` class from `java.lang.reflect`. This class provides methods to dynamically create and access arrays. For instance, arrays can be identified using `isArray()`, created with `Array.newInstance()`, and elements can be set or retrieved using methods like `Array.set()` and `Array.get()`. This enables flexible manipulation of arrays, such as setting or getting values at specific indices, dynamically during program execution .

You might also like