Monday, April 20, 2015
Reflection in Java Example
Manchu Bhargavi
12:42 AM
java
,
methods in reflection
,
reflection
,
reflection in java example
No comments
:
Hi,
Reflection.java :
Example.java :
Reflection in Java
Example :
Reflection
is most powerful concept. It is used to get classes and methods, interfaces,
fields, constructors, annotations in the runtime. Even if dono what are classes
and methods are available.
Reflection is language ability to inspect and dynamically call the
classes,methods,attrtitubes,etc at runtime.
Reflection in java is used to inspect and modify the
structure at runtime behavior of applications.
Syntax for Reflection
:
Method[] methods=myClass.class.getMethods();
For(Method method
:methods){
System.out.println(“Method =”method.getName());
}
Examples for
Reflection in classes :
1.Create the java Project in Eclipse
2.Create the java class called Reflection.java
package com.example.reflect;
public class Reflection {
private
int count=0;
public void result(){
System.out.println("The
reflection is used to get all methods and class in runtime");
}
public void
printMethods(String name){
System.out.println("this
method is shows with one param"+name);
}
public void printIntMethod(int
no){
System.out.println("All
methods in print methods are"+no);
}
public void
getAllMethods(){
System.out.println("This
is to get all methods");
}
public void setMethod(int
no){
no=count;
System.out.println("The
reflection method is"+no);
}
}
3. create the another class called Example.java
package com.example.reflect;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class Example {
public static void main(String[] args) {
Method[] method =
Reflection.class.getDeclaredMethods();
Reflection rf = new Reflection();
//printing
all the methods from the another class durning runtime
System.out.println("start");
for
(Method me : method) {
System.out.println("The
methods are \t" + me);
}Method[]
mMethod=rf.getClass().getMethods();
//calling
the refelection method
try
{
System.out.println("here
only calling method will print");
mMethod[0].invoke(rf,
null);
System.out.println("Ending
method is as follows");
}
catch (IllegalAccessException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e) {
//
TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Exit")
} }
4.Run the application and check the output
Subscribe to:
Post Comments
(
Atom
)
No comments :
Post a Comment