Home Java Reflect Setting Fields Information of a class using Reflection
Questions:Ask|Latest


 
 

Share on Google+Share on Google+

Setting Fields Information of a class using Reflection

Advertisement
As in our previous example we have seen that we can get field values of a class by using the Field class. Now we can also set different field values of that class by using set() method.

Setting Fields Information of a class using Reflection

     

As in our previous example we have seen that we can get field values of a class by using the Field class. Now we can also set different field values of that class by using set() method.

In our class SettingField we have created an object of "Rectangle" and we can get fields of that object by using getField() method and we can retrieve values of that fields by get() method. Now we can set fields value by using set() methods. 

    xfield.setInt(rect,new Integer(10));
  yfield.setInt(rect,new Integer(10));
  heightField.setInt(rect,new Integer(60));
  widthField.setInt(rect,new Integer(80));

Above lines of code sets x-axis, y-axis, height, width field values. Since we are setting integer values to its field so I have used setInt() method. Here is the example code for SettingField class :

SettingField.java

import java.awt.*;
import java.lang.reflect.*;

public class SettingField{
  public static void main(String[] argsthrows Exception{
  Rectangle rect=new Rectangle();
  Field xfield = rect.getClass().getField("x");
  Field yfield = rect.getClass().getField("y");
  Field heightField = rect.getClass().getField("height");
  Field widthField = rect.getClass().getField("width");
  System.out.println("---->> Before Setting Values <<----");
  System.out.println("X Value = "+ xfield.getInt(rect));
  System.out.println("Y Value = "+ yfield.getInt(rect));
  System.out.println("Height Value = "+ heightField.getInt(rect));
  System.out.println("Width Value = "+ widthField.getInt(rect));
  xfield.setInt(rect,new Integer(10));
  yfield.setInt(rect,new Integer(10));
  heightField.setInt(rect,new Integer(60));
  widthField.setInt(rect,new Integer(80));
  System.out.println("---->> After Setting Values <<----");
  System.out.println("X Value = "+ xfield.getInt(rect));
  System.out.println("Y Value = "+ yfield.getInt(rect));
  System.out.println("Height Value = "+ heightField.getInt(rect));
  System.out.println("Width Value = "+ widthField.getInt(rect));
 }
}

Output:

Download Source Code

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: September 10, 2008

Ask Questions?    Discuss: Setting Fields Information of a class using Reflection  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
DMCA.com