Showing posts with label Reflection. Show all posts
Showing posts with label Reflection. Show all posts
Sunday, February 16, 2014
Today I will show that how the power of reflection can bypass encapsulation. This is excellent feature in Java. You must have read and experienced that you cannot create instances of class with private constructors using "new" keyword outside that class. But using reflection you can do mit very easily.And using that we can call any methods and do as we wish. To do that we have to follow these steps :
- Create the Class class instance of the specified class using Class.forName() or <Class-Name>.class
- Create the Constructor instance from the Class instance using getDeclaredConstructor()
- Call the setAccessible() on constructor object and set to true. This is the most important step as failing it wont allow you to access the private constructor.
- Call newInstance() method on the constructor object which will return a reference to Object class. That's it. Dow what you wish with this reference.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
import java.lang.reflect.Constructor; class PrivateCons { private String i; private PrivateCons(String i){ this.i=i; } @Override public String toString(){ return "I am "+i; } } public class PrivateConsReflect{ public static void main(String[] args) throws Exception{ Class c=PrivateCons.class; //getting Class class instance Constructor cons=c.getDeclaredConstructor(String.class); //getting constructor cons.setAccessible(true); //setting true to access private feature Object pc=cons.newInstance("5"); //creating instance of the class System.out.println(pc); //printing object } }
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Labels:Reflection | 0
comments
Sunday, September 1, 2013
In our vlast posts we only concentrated on sniffing class declaration and its members. But this time we will go beyond it and try to get and set field values of a given class using Java Reflection.For this we just need an instance of a class. Though here we will deal with public fields only and someone might think that we can get and set field values in thes cases directly using instance of that class. But this is not the actual case in real situation. This is done only in places where directly we cannot set thopse values as in case of private members. So here we have used method getDeclaredField() (we will deal with private members later). Here we will just show that once you have the class refernce and the instance of a particualr class you can get and set the field values whether its an integer,float,string or array. There are seperate methods for different primitive data types like getInt() and setInt() for int , getLong() and setLong() for long and so on. But for data types other than primiotive ones you have to use get() and set() methods.
Here in our demo we jave created a class Person with fields of type int, String and a String array. So you will be able to uinderstand clearly how to use different methods depending on data type.
-------------------------------------------------------------------------------------------------------------------------
import java.lang.reflect.Field;
import java.util.Arrays;
import static java.lang.System.out;
class Person{
public int id=1521;
public String name="Luther";
public String hobbies[]={"cricket","music"};
}
public class FieldChanger {
public static void main(String[] args) {
try{
Class c=Person.class; //getting class reference
Person pobj=new Person();
Field id=c.getDeclaredField("id"); //getting field reference
out.println("BEFORE : id = "+id.getInt(pobj)); //getting initial int value
id.setInt(pobj, 1926); //setting a new int value
out.println(" AFTER : id = "+id.getInt(pobj));
Field name=c.getDeclaredField("name");
out.println("BEFORE : name = "+name.get(pobj)); //getting initial String value
name.set(pobj, "Jennifer"); //setting a new String value
out.println(" AFTER : name = "+name.get(pobj));
Field hobbies=c.getDeclaredField("hobbies");
//showing initial array values
out.println("BEFORE : hobbies = "+Arrays.asList(pobj.hobbies));
String[] nhob={"football"};
hobbies.set(pobj, nhob); //setting new values for array
out.println(" AFTER : hobbies = "+Arrays.asList(pobj.hobbies));
}catch(NoSuchFieldException|
IllegalAccessException e){ }
}
}
Here in our demo we jave created a class Person with fields of type int, String and a String array. So you will be able to uinderstand clearly how to use different methods depending on data type.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------import java.lang.reflect.Field;
import java.util.Arrays;
import static java.lang.System.out;
class Person{
public int id=1521;
public String name="Luther";
public String hobbies[]={"cricket","music"};
}
public class FieldChanger {
public static void main(String[] args) {
try{
Class c=Person.class; //getting class reference
Person pobj=new Person();
Field id=c.getDeclaredField("id"); //getting field reference
out.println("BEFORE : id = "+id.getInt(pobj)); //getting initial int value
id.setInt(pobj, 1926); //setting a new int value
out.println(" AFTER : id = "+id.getInt(pobj));
Field name=c.getDeclaredField("name");
out.println("BEFORE : name = "+name.get(pobj)); //getting initial String value
name.set(pobj, "Jennifer"); //setting a new String value
out.println(" AFTER : name = "+name.get(pobj));
Field hobbies=c.getDeclaredField("hobbies");
//showing initial array values
out.println("BEFORE : hobbies = "+Arrays.asList(pobj.hobbies));
String[] nhob={"football"};
hobbies.set(pobj, nhob); //setting new values for array
out.println(" AFTER : hobbies = "+Arrays.asList(pobj.hobbies));
}catch(NoSuchFieldException|
IllegalAccessException e){ }
}
}
-------------------------------------------------------------------------------------------------------------------------
Output
-------------------------------------------------------------------------------------------------------------------------
BEFORE : id = 1521
AFTER : id = 1926
BEFORE : name = Luther
AFTER : name = Jennifer
BEFORE : hobbies = [cricket, music]
AFTER : hobbies = [football]
-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
Happy coding :)
Labels:Reflection | 0
comments
Saturday, August 10, 2013
In our last post we were only concerned in retrieving the declaration details of any class. Today I will go further and try to sniff inside any class. So today I will show you how you can retrieve all the constructors, fields and methods of any class using Java Reflection. For now we will only try to discover all the public members of a class and deal with private ones later. The java.lang.Class provides suitable methods for discovering the members. Here in our sample code we will first take as input the concerned class name and load it using Class.forName(). Then in order to get all its public constructors we vwill use getConstructors(), for fields use getFields() and for methods use getMethods(). An important thing to mention here is that these will return all the public members declared in that class as well as those inherited from its parent. You wont be able to retrieve the private members declarec using these methods. In order to get private members also use getDeclaredConstructors(), getDeclaredFields() and getDeclaredMethods(); but in this case you wont be able to get the inherited members.
--------------------------------------------------------------------------------------------------------------------------
import static java.lang.System.out;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ClassSniffer {
public static void main(String[] args) {
out.print("Enter Class Name : ");
String cname=System.console().readLine();
try {
Class c=Class.forName(cname);
out.println("\n------OUTPUT------");
//getting all constructors
out.println("\nConstructors : ");
Constructor<?> cons[]=c.getConstructors();
for(Constructor<?> con : cons)
out.println(" "+con);
//getting all fields
out.println("\nFields : ");
Field fs[]=c.getFields();
if(fs.length>0)
for(Field f : fs)
out.println(" "+f);
else
out.println(" --No Fields Declared--");
//getting all methods
out.println("\nMethods : ");
Method ms[]=c.getMethods();
for(Method m : ms)
out.println(" "+m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import static java.lang.System.out;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ClassSniffer {
public static void main(String[] args) {
out.print("Enter Class Name : ");
String cname=System.console().readLine();
try {
Class c=Class.forName(cname);
out.println("\n------OUTPUT------");
//getting all constructors
out.println("\nConstructors : ");
Constructor<?> cons[]=c.getConstructors();
for(Constructor<?> con : cons)
out.println(" "+con);
//getting all fields
out.println("\nFields : ");
Field fs[]=c.getFields();
if(fs.length>0)
for(Field f : fs)
out.println(" "+f);
else
out.println(" --No Fields Declared--");
//getting all methods
out.println("\nMethods : ");
Method ms[]=c.getMethods();
for(Method m : ms)
out.println(" "+m);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------
Enter Class Name : ClassSniffer
------OUTPUT------
Constructors :
public ClassSniffer()
Fields :
--No Fields Declared--
Methods :
public static void ClassSniffer.main(java.lang.String[])
public final void java.lang.Object.wait(long,int) throws java.lang.Interrupted
Exception
public final native void java.lang.Object.wait(long) throws java.lang.Interrup
tedException
public final void java.lang.Object.wait() throws java.lang.InterruptedExceptio
n
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()
NOTE : Here you can see that the methods inherited from Object class are also listed. The name of the class is mentioned just before the method name which shows the methods inherited from other class and those declared in the class itself. Try running this code with getDeclaredConstructors(), getDeclaredFields() and getDeclaredMethods() instead and see the output.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Reflection | 0
comments
Thursday, August 8, 2013
Today I will show you how to retrieve all the declaration components of a class using Java Reflection. The declaration components means the modifiers, the generic type parameters, implemented interfaces, classes inherited i.e. inheritance path and all the annotations declared. These are all the meta informations related with a class. We can get all modifiers using method getModufiers(). The different modifiers include private, protected, public, static, final, abstract etc. We can get annotations using getAnnotations(). We can get type parameters using getTypeParameters() while interfaces using getGenericInterfaces() and super-class using getSuperClass().
Here in the example we will take input from user the fully qualified class name and then print all the declaration components of that class using the methods mentioned above and thus sniff class declaration. If the class name eneterd is not found then it will throw ClassNotFoundException.
--------------------------------------------------------------------------------------------------------------------------
import java.io.Console;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
public class ClassDeclarationSniffer {
public static void main(String[] args) {
Console console=System.console();
System.out.print("Enter Class Name : ");
String cname=console.readLine(); //reading class name
try {
Class<?> c=Class.forName(cname); //loading class
out.println("\n------OUTPUT------");
out.println("Class : "+c.getCanonicalName());
//getting all modifiers
out.println("\nModifiers : "+Modifier.toString(c.getModifiers()));
//getting generic type parameters
out.print("\nType Parameters : ");
TypeVariable[] tv = c.getTypeParameters();
if (tv.length != 0)
for (TypeVariable t : tv)
out.print(t.getName()+" ");
else
out.print(" -- No Type Parameters --");
//getting all implemented interfaces
out.println("\n\nImplemented Interfaces :");
Type[] intfs = c.getGenericInterfaces();
if (intfs.length != 0)
for (Type intf : intfs)
out.println(" "+intf.toString());
else
out.println(" -- No Implemented Interfaces --");
//getting inheritance hierarchy
out.println("\nInheritance Path : ");
List<Class> lst = new ArrayList<Class>();
printParent(c, lst);
if (lst.size() != 0)
for (Class<?> parent : lst)
out.println(" "+parent.getCanonicalName());
else
out.println(" -- No Super Classes --");
//getting all annotations
out.println("\nAnnotations : ");
Annotation[] anns = c.getAnnotations();
if (anns.length != 0)
for (Annotation a : anns)
out.println(" "+a.toString());
else
out.println(" -- No Annotations --");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void printParent(Class<?> c, List<Class> l) {
Class<?> parent = c.getSuperclass(); //getting superclass
if (parent != null) {
l.add(parent); //adding to hierarchy list
printParent(parent, l); //recursive calling for another parent
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Enter Class Name : java.util.ArrayList
------OUTPUT------
Class : java.util.ArrayList
Modifiers : public
Type Parameters : E
Implemented Interfaces :
java.util.List<E>
interface java.util.RandomAccess
interface java.lang.Cloneable
interface java.io.Serializable
Inheritance Path :
java.util.AbstractList
java.util.AbstractCollection
java.lang.Object
Annotations :
-- No Annotations --
Here in the example we will take input from user the fully qualified class name and then print all the declaration components of that class using the methods mentioned above and thus sniff class declaration. If the class name eneterd is not found then it will throw ClassNotFoundException.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.io.Console;
import java.lang.annotation.Annotation;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.List;
import static java.lang.System.out;
public class ClassDeclarationSniffer {
public static void main(String[] args) {
Console console=System.console();
System.out.print("Enter Class Name : ");
String cname=console.readLine(); //reading class name
try {
Class<?> c=Class.forName(cname); //loading class
out.println("\n------OUTPUT------");
out.println("Class : "+c.getCanonicalName());
//getting all modifiers
out.println("\nModifiers : "+Modifier.toString(c.getModifiers()));
//getting generic type parameters
out.print("\nType Parameters : ");
TypeVariable[] tv = c.getTypeParameters();
if (tv.length != 0)
for (TypeVariable t : tv)
out.print(t.getName()+" ");
else
out.print(" -- No Type Parameters --");
//getting all implemented interfaces
out.println("\n\nImplemented Interfaces :");
Type[] intfs = c.getGenericInterfaces();
if (intfs.length != 0)
for (Type intf : intfs)
out.println(" "+intf.toString());
else
out.println(" -- No Implemented Interfaces --");
//getting inheritance hierarchy
out.println("\nInheritance Path : ");
List<Class> lst = new ArrayList<Class>();
printParent(c, lst);
if (lst.size() != 0)
for (Class<?> parent : lst)
out.println(" "+parent.getCanonicalName());
else
out.println(" -- No Super Classes --");
//getting all annotations
out.println("\nAnnotations : ");
Annotation[] anns = c.getAnnotations();
if (anns.length != 0)
for (Annotation a : anns)
out.println(" "+a.toString());
else
out.println(" -- No Annotations --");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static void printParent(Class<?> c, List<Class> l) {
Class<?> parent = c.getSuperclass(); //getting superclass
if (parent != null) {
l.add(parent); //adding to hierarchy list
printParent(parent, l); //recursive calling for another parent
}
}
}
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------Enter Class Name : java.util.ArrayList
------OUTPUT------
Class : java.util.ArrayList
Modifiers : public
Type Parameters : E
Implemented Interfaces :
java.util.List<E>
interface java.util.RandomAccess
interface java.lang.Cloneable
interface java.io.Serializable
Inheritance Path :
java.util.AbstractList
java.util.AbstractCollection
java.lang.Object
Annotations :
-- No Annotations --
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------
Labels:Reflection | 0
comments
Subscribe to:
Posts
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...