Java Reflection API
Reflection is a feature in the Java programming language. Java's Reflection API's makes it possible to inspect classes, interfaces, fields and methods at runtime, without knowing the names of the classes, methods etc. at compile time. It is also possible to instantiate new objects, invoke methods and get/set field values using reflection.
Example.java
package com.jsl.core; import java.lang.reflect.Method; class Example{ public void display(){ System.out.println("The Display Method"); } public void show(){ System.out.println("The Show Method"); } private void print(){ System.out.println("The Print Method"); } }
GetMethods.java
public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.Example"); Method method[]=c.getDeclaredMethods(); for(Method name:method) System.out.println(name); }catch (Exception e) { System.out.println(e); } } }
output
private void com.jsl.core.Example.print() public void com.jsl.core.Example.display() public void com.jsl.core.Example.show()
getDeclaredClasses()
Returns an array of
Class
objects reflecting all the classes and interfaces declared as members of the class represented by this Class
object. This includes public, protected, default access, and private classes and interfaces declared by the class, but excludes inherited classes and interfaces. This method returns an array of length 0 if the class declares no classes or interfaces as members, or if this Class
object represents a primitive type, an array class, or void.try{ Class c=Class.forName("com.jsl.core.Example"); Method method[]=c.getMethods(); for(Method name:method) System.out.println(name); }catch (Exception e) { System.out.println(e); }
Returns an array containing
Method
objects reflecting all the public member methods of the class or interface represented by this Class
object, including those declared by the class or interface and and those inherited from superclasses and superinterfaces. The elements in the array returned are not sorted and are not in any particular order. This method returns an array of length 0 if this Class
object represents a class or interface that has no public member methods, or if this Class
object represents an array class, primitive type, or void. isInstance( )
Determines if the specified
Object
is assignment-compatible with the object represented by this Class
. This method is the dynamic equivalent of the Java language instanceof
operator. The method returns true
if the specified Object
argument is non-null and can be cast to the reference type represented by this Class
object without raising a ClassCastException.
It returns false
otherwise. public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.Example"); boolean b1=c.isInstance(new Example()); System.out.println(b1); boolean b2=c.isInstance(new String()); System.out.println(b2); }catch (Exception e) { System.out.println(e); } } }
output:
true false
Program to find the methods of the class.
package com.jsl.core; import java.lang.reflect.Method; import java.lang.reflect.Modifier; class Example{ public void display(){ System.out.println("The Display Method"); } public void show(int a,int b){ System.out.println("The Show Method"); } private void print(Object object){ System.out.println("The Print Method"); } } public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.Example"); Method methods[]=c.getDeclaredMethods(); for(Method method:methods){ System.out.println("***********************************************"); System.out.println("Method modifier :" + Modifier.toString(method.getModifiers())); System.out.println("Method name : "+method.getName()); System.out.println("Metho return type: "+method.getReturnType()); Class params[]=method.getParameterTypes(); for(int i=0;i < params.length;i++){ System.out.println("Param [i] "+" = "+params[i]); } } }catch (Exception e) { System.out.println(e); } } }
output:
****************************************************** Method modifier :private Method name : print Metho return type: void Param 0 = class java.lang.Object ****************************************************** Method modifier :public Method name : display Metho return type: void ****************************************************** Method modifier :public Method name : show Metho return type: void Param 0 = int Param 1 = int
Obtaining Information About Constructors
A similar approach is used to find out about the constructors of a class.
package com.jsl.core; import java.lang.reflect.Constructor; class Example{ private Example(){ } private Example(int a,int b){ } private Example(String name,String email){ } } public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.Example"); Constructor constructors[]=c.getDeclaredConstructors(); for(Constructor constructor:constructors) System.out.println(constructor); }catch (Exception e) { System.out.println(e); } } }
output:
private com.jsl.core.Example() private com.jsl.core.Example(int,int) private com.jsl.core.Example(java.lang.String,java.lang.String)
Finding Out About Class Fields
It's also possible to find out which data fields are defined in a class.
package com.jsl.core; import java.lang.reflect.Field; import java.lang.reflect.Modifier; class Example{ private int val=23; final String name="jsltech"; private final int id=1001; private static int count=9999; } public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.Example"); Field fields[]=c.getDeclaredFields(); for(int i=0;i < fields.length;i++){ Field field=fields[i]; System.out.println("Field Name : "+field.getName()); System.out.println("Field Modifier: "+Modifier. toString(field.getModifiers())); System.out.println("Filed Type :"+field.getType()); System.out.println("************************************"); } }catch (Exception e) { System.out.println(e); } } }
Output:
Field Name : val Field Modifier: private Filed Type :int ************************************ Field Name : name Field Modifier: final Filed Type :class java.lang.String ************************************ Field Name : id Field Modifier: private final Filed Type :int ************************************ Field Name : count Field Modifier: private static Filed Type :int ************************************
To know about the super class and implemented interfaces
package com.jsl.core; class One{ } interface InterfaceTwo{ } interface InterfaceOne{ } class Two extends One implements InterfaceOne{ } public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.Two"); System.out.println("The super class is : "+c.getSuperclass()); Class cls[]=c.getInterfaces(); System.out.println("The Implemented interface are :"); for(Class cl:cls){ System.out.println(cl); } }catch (Exception e) { System.out.println(e); } } }
output:
The super class is : class com.jsl.core.One The Implemented interface are : interface com.jsl.core.InterfaceOne interface com.jsl.core.InterfaceTwo
Invoking the method by Name
so far the method can be called by using object name or classes name, we can invoke the method by using reflection api, here is simple example to invoke the method
package com.jsl.core; import java.lang.reflect.Method; class One{ public String fullName(String fname,String lname){ return fname.concat(" ").concat(lname); } } public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.One"); Method method=c.getMethod("fullName",new Class[] {String.class,String.class}); String fullName=(String)method.invoke(new One(),new Object[]{"JSL","Tech"}); System.out.println("The full name is :"+fullName); }catch (Exception e) { System.out.println(e); } } }Output:
The full name is : JSL Tech
Creating New Objects
There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction).
package com.jsl.core; import java.lang.reflect.Constructor; class One{ public One(){ System.out.println(" The constructor is invoked "); } public String fullName(String fname,String lname){ return fname.concat(" ").concat(lname); } } public class GetMethods { public static void main(String[] args) { try{ Class c=Class.forName("com.jsl.core.One"); Constructor constructor=c.getDeclaredConstructor(); One obj=(One) c.newInstance(); System.out.println(obj.fullName("JSL", "Tech")); }catch (Exception e) { System.out.println(e); } } }
Output:
The constructor is invoked JSL Tech
Changing the values of field by using refilection api
package com.jsl.core; import java.lang.reflect.Field; class One{ public String name="miani"; } public class GetMethods { public static void main(String args[]){ try { Class c=Class.forName("com.jsl.core.One"); Field filed=c.getField("name"); One obj=new One(); System.out.println("The name is :"+obj.name); filed.set(obj, "Jsl Tech"); System.out.println("The name after modification :"+obj.name); }catch (Throwable e) { System.err.println(e); } } }
output:
The name is :miani The name after modification :Jsl Tech
No comments:
Post a Comment