·  JAVA – Syntax – Terms – Reflection

 

- Info:

  - Reflection enables you to get information of class: name, methods and properties.

  - You can run methods and take properties values.

 

- Procedure:

  - Create JAVA Console Application Test.java

 

    Test.java

    import java.lang.reflect.*;

    import java.lang.Class;

    

    class Unknown {

      public int height = 176;

      public int weight = 75;

      public void noArgs()      {    System.out.println("noArgs>Hello!");  }

      public void oneArg(int i) {    System.out.println("oneArg>"+i);  }

    }

    

    public class Test {

     

      public static void main(String[] args) {

        try{

          Unknown   obj         = new Unknown();

          Class     objectClass = obj.getClass();

          String    className   = objectClass.getName();

          Method[]  classMethods= objectClass.getMethods();

          Field[]   classFields = objectClass.getFields();    //Only public ones are displayed.

          System.out.println("className>"+className);

          

          //All methods.

          for(int i=0;i<classMethods.length;i++){

            System.out.println("methodName>"+classMethods[i].getName());

          }

    

          //All fields.

          for(int i=0;i<classFields.length;i++){

            System.out.println("fieldName>"+classFields[i].getName());

          }

    

          //height.

          Field     height = classFields[0];

          System.out.println("height="+height.get(obj));

          

          //width.

          Field     width = classFields[1];

          System.out.println("width="+width.get(obj));

          

          //noArgs.

          Method    noArgs = classMethods[0];

          Object[]  params1 = null;

          noArgs.invoke(obj,params1);

    

          //oneArgs.

          Method    oneArg = classMethods[1];

          Integer[]  params2 = new Integer[1];

          params2[0] = new Integer(12);

          oneArg.invoke(obj,params2); 

          

        }

        catch(Exception e){}

    

      }

    }