Ads Sponsored By Google :)

Tuesday, 29 January 2013

how can we Find|Finding variables|fields of Class in java using reflection with example


Finding variables of Class in java using reflection how can we Find variables of Class in java using reflection
Finding variables of Class in java using reflection with example how can we Find variables of Class in java using reflection with example Finding Fields of Class in java using reflection Finding Fields of Class in java with example using reflection can we find variables of class in java using reflection can we find variables of class in java with example

    Finding Fields of Class:

            A Field is nothing but an instance variable in java we can create variables either in a 
      class or in a method. We call variables either in a class or in a method. We call variable 
     declared in a class as instance variable and variable declared in a method are called local 
     variables. By using reflection it is possible to find instance variable META DATA(fields 
     META DATA).
     
          public class A
        {
             int x;              //x (Class Scope) instance variable or field
             void m1()
           {
              int y;            // y(method scope) local variable
              if(condition)
            {
               int z;         //z(Block scope) or local variable
             }
           }
        }

        To get META DATA  of fields we call getFields() it returns an array of field of type.
        Field f[]=c.getFields();

        Field is a class given in java.lang and java.lang.reflect package java.lang.reflect is sub 
     package java.lang and we call this java.lang.reflect as a reflection API.
     
     C----- > API ------ >header Files ------ > (set of functions)
     C++--- >API ------ >header Files ------ >(set of functions and classes).
    Java --- >API ------ >header Files------ >(set of classes & interfaces sub packages).

          To find reflection on fields we need to get a field and then we need to get one by one 
      field object from that array we need to get the data type and variable name.

      For Example:

       // ReflectDemo4.java

         public class ReflectDemo4{
             public static void main(String argra[]) {
                  Class c=Class.forName(args[0]);
                  Field f[]=c.getFields();
                  for(int i=0;i<f.length;i++){
                    String s1=f[1].getType().getName();
                    String s2=f[i].getName();
                    System.out.println(s1+”     “+s2);
                   }
                 }
               }

     Output:

              C:\> javac ReflectDemo3.java
              C:\> java ReflectDemo3 java.lang.Thread
                       int MIN_PRIORITY
                       int NORM_PRIORITY
                       int MAX_PRIORITY

No comments:

Post a Comment

LinkWithin