Thursday, October 24, 2013

Example for Java Reflect

Create the below Class ..


public class JavaClassSpy implements Serializable{
    public JavaClassSpy(){
    }
    public JavaClassSpy(int a, float f) {
        super();
        this.a = a;
        this.f = f;
    }
    private int a;
    private float f;
    public boolean b = true;
    public String name = "Alice";
    public List<Integer> list;
    public void printHello(){
        System.out.println("Hello!!");
        System.out.println("a :" + this.a);
        System.out.println("f :"+ this.f);
        System.out.println("b :"+ this.b);
        System.out.println("name :"+ this.name);
        System.out.println("list :"+ this.list);
    }
    public static void main(String... args) {}
}


Write a program that prints the following:
  • name of the class.
  • modifiers of the class.
  • package of the class.
  • fields of the class (list the field names/data types/modifiers).
  • list of all the private/public field names in the class.
  • methods of the class (name and return type).
  • interfaces implemented by the class (name).
  • constructors.
  • super class.
  • Create an instance of the class.
  • Set all field values in the new instance (with some values).
  • Invoke all public methods using the new instance.
Here's a sample output

assignment10.JavaClassSpy
public
package assignment10

-----Fields-----
private int a
private float f
public boolean b
public String name
public List list

-----Methods-----
public static void main(class [Ljava.lang.String;)
public void printHello()

----Interface-----
interface java.io.Serializable

-----Constructors-----
public assignment10.JavaClassSpy()
public assignment10.JavaClassSpy(int, float)

SuperClass: class java.lang.Object

-----Invoking Methods-----

Hello!!
a :10
f :23.56
b :false
name :Shaeed
list :[0, 1, 2, 3]

Program:


import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.List;

public class JavaClassSpy implements Serializable {
 private int a;
 private float f;
 public boolean b = true;
 public String name = "Alice";
 public List<Integer> list;

 public JavaClassSpy(){}
 public JavaClassSpy(int a, float f){
  this.a=a;
  this.f=f;
 }

 public void printHello(){
  System.out.println("Hello!!");
  System.out.println("a :" + this.a);
  System.out.println("f :"+ this.f);
  System.out.println("b :"+ this.b);
  System.out.println("name :"+ this.name);
  System.out.println("list :"+ this.list);
 }
 
 public static void main(String[] args){
  System.out.println("In main method of JavaClassSpy");
 }
}  
Test Class:

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

//Importing JavaSpy Class
import JavaClassSpy;

public class TestClass {

 public static void main(String [] args) throws InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{

  Class<JavaClassSpy> ref = JavaClassSpy.class;
  System.out.println(ref.getName());
  System.out.println(Modifier.toString(ref.getModifiers()));
  System.out.println(ref.getPackage());

  //Fields
  Field[] fields = ref.getDeclaredFields();
  System.out.println("\n-----Fields-----");
  for(Field f : fields){
   System.out.printf("%s %s %s\n",Modifier.toString(f.getModifiers()),f.getType().getSimpleName(),f.getName());
  }

  //Methods
  Method[] methods = ref.getDeclaredMethods();
  System.out.println("\n-----Methods-----");
  for(Method m:methods){
   System.out.printf("%s %s %s(",Modifier.toString(m.getModifiers()),m.getReturnType(), m.getName());
   
   Class<?>[] par = m.getParameterTypes();
   if(par.length>0){
    System.out.print(par[0]);
    for(int i=1;i<par.length-1;i++)
     System.out.print(", "+par[i].toString());
    if(par.length>1)
    System.out.print(", "+par[par.length-1]);
   }
   System.out.println(")");
  }

  //Interface
  Class<?>[] intrfc=ref.getInterfaces();
  System.out.println("\n----Interface-----");
  for(Class<?> s:intrfc)
   System.out.println(s.toString());

  //Constructors
  Constructor<?>[] constr = ref.getDeclaredConstructors();
  System.out.println("\n-----Constructors-----");
  
  for(Constructor<?> con:constr){
   System.out.printf("%s %s(",Modifier.toString(con.getModifiers()),con.getName());
   
   Class<?>[] par = con.getParameterTypes();
   if(par.length>0){
    System.out.print(par[0]);
    for(int i=1;i<par.length-1;i++)
     System.out.print(", "+par[i]);
    if(par.length>1)
    System.out.print(", "+par[par.length-1]);
   }
   System.out.println(")");
  }
  
  //SuperClass
  System.out.println("\nSuperClass: "+ref.getSuperclass());
  
  //Instance of the class
  Object obj = ref.newInstance();
  
  //accessing field and setting values
  Field[] fl = new Field[fields.length];
  for(int i=0;i<fields.length;i++){
   
   fl[i]=ref.getDeclaredField(fields[i].getName());
   fl[i].setAccessible(true);
   if(fields[i].getType().getSimpleName().equals("int"))
    fl[i].set(obj, 10);
   else if(fields[i].getType().getSimpleName().equals("String"))
    fl[i].set(obj, "Shaeed");
   else if(fields[i].getType().getSimpleName().equals("float"))
    fl[i].set(obj, 23.56f);
   else if(fields[i].getType().getSimpleName().equals("boolean"))
    fl[i].set(obj, false);
   else if(fields[i].getType().getSimpleName().equals("List")){
    fl[i].set(obj, new ArrayList<Integer>());
    List<Integer> ll = (List)fl[i].get(obj);
    for(int j=0;j<i;j++){
     ll.add(j);
    }
   }
  }
  
  //Calling methods
  System.out.println("\n-----Invoking Methods-----");
  System.out.println();
  for(Method m:methods){
   if(!(m.getName().equals("main"))){
    Method mCall = ref.getDeclaredMethod(m.getName(),null);
    mCall.invoke(obj);
   }
  }
 }
}

No comments:

Post a Comment