Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself (at runtime), and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.
This program will find all the methods of java.util.List class
import java.lang.reflect.*;
public class Fun {
public static void main(String args[])
{
try {
Class c = Class.forName("java.util.List");
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
}
catch (Throwable e) {
System.err.println(e);
} } }
We can use reflection to know about the class.
Another Example Which will detect the instance variable of a class.
import java.lang.reflect.*;
public class Fun {
void xxx(){}
int x;
static long z=111111;
String y;
public static void main(String args[])throws Exception
{
try {
Class c = Class.forName("Fun");
Field m[] = c.getDeclaredFields();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].getName()+" "+m[i].getType());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
OUTPUT:
x int
z long
y class java.lang.String
Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine.
This program will find all the methods of java.util.List class
import java.lang.reflect.*;
public class Fun {
public static void main(String args[])
{
try {
Class c = Class.forName("java.util.List");
Method m[] = c.getDeclaredMethods();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].toString());
}
catch (Throwable e) {
System.err.println(e);
} } }
We can use reflection to know about the class.
Another Example Which will detect the instance variable of a class.
import java.lang.reflect.*;
public class Fun {
void xxx(){}
int x;
static long z=111111;
String y;
public static void main(String args[])throws Exception
{
try {
Class c = Class.forName("Fun");
Field m[] = c.getDeclaredFields();
for (int i = 0; i < m.length; i++)
System.out.println(m[i].getName()+" "+m[i].getType());
}
catch (Throwable e) {
System.err.println(e);
}
}
}
OUTPUT:
x int
z long
y class java.lang.String
No comments:
Post a Comment