A feature which allows the program to analyse the program at run time. You can modify the structure and behaviour of the program dynamically.
Features:
Creating objects:
A new object can be created at runtime. The object is
instantiated using the constructor.
Accessing Class information:
It uses java.lang package to get the class information. It also
gives the details about member variables, methods, constructors and modifiers.
Manipulating Fields:
A class ‘Field’ is
used to get and set the field values. Even you can modify the private value.
Dynamic method invocation:
‘Method’ class is used to invoke the methods on objects. This
handles the methods without the name also.
Inspect annotations:
It
analyses the classes, methods, fields and other members. This is used to build
the frameworks and libraries.
Create the java program to implement the java reflection is
given below…..
Program implementation:
- · Include the built in packages.
- · Create a class with main() function.
- · Using a try catch block, include the coding.
- · Get the class name and assign to the class object.
- · Using method object,assign the declaredmethods.
- · Finally,method object is used to getName of the methods and display the names of the class.
Program:
import java.lang.reflect.Method;
public class ReflectionEg {
public static void
main(String[] args) {
try {
//This
statement gives you the Class object for the class
Class<?> clas1 = Class.forName("java.util.ArrayList");
Method[]
methods = clas1.getDeclaredMethods();
for
(Method method1 : methods) {
System.out.println("Method name: " + method1.getName());
}
e.printStackTrace();
}
}
}
Output:
C:\raji\blog>javac ReflectionEg.java
C:\raji\blog>java ReflectionEg
Method name: remove
Method name: remove
Method name: size
Method name: get
Method name: equals
Method name: hashCode
Method name: clone
Method name: sort
Method name: indexOf
Method name: clear
Method name: lastIndexOf
Method name: isEmpty
Method name: replaceAll
Method name: add
……………………………………….
That’s all. The java program to illustrate java reflection
is implemented successfully. Happy coding!!!
No comments:
Post a Comment