Tuesday 25 July 2017

Whitebox: get all the fields of a class

Whitebox class provides 'getFields' method to get all the fields of a class.

Following statement return te field references for the properties "noOfObjects", "name", "version".
Field[] fields = Whitebox.getFields(Model.class, "noOfObjects", "name", "version");

Following is the complete working application.

Model.java
package com.sample.model;

public class Model {

 private static int noOfObjects = 0;

 private String name = "";
 private String version = "";

 public Model() {
  this("Sample App", "1.0");
 }

 public Model(String name) {

  this(name, "1.0");

 }

 public Model(String name, String version) {
  noOfObjects++;
  this.name = name;
  this.version = version;
 }
}


ModelTest.java
package com.sample.model;

import java.lang.reflect.Field;

import org.powermock.reflect.Whitebox;

public class ModelTest {

 private static void printObjectInfo(Model model, Field[] fields)
   throws IllegalArgumentException, IllegalAccessException {
  System.out.println("*******************************");
  for (Field field : fields) {
   String name = field.getName();

   if ("noOfObjects".equals(name)) {
    System.out.println("noOfObjects :  " + field.getInt(model));
   } else if ("name".equals(name)) {
    System.out.println("name :  " + field.get(model));
   } else if ("version".equals(name)) {
    System.out.println("version :  " + field.get(model));
   }
  }
 }

 public static void main(String args[]) throws IllegalArgumentException, IllegalAccessException {
  Field[] fields = Whitebox.getFields(Model.class, "noOfObjects", "name", "version");

  Model model1 = new Model();
  System.out.println("After crating model object1");
  printObjectInfo(model1, fields);

  System.out.println("\nAfter crating model object2");
  Model model2 = new Model("4-Factor Auth");
  printObjectInfo(model2, fields);

  System.out.println("\nAfter crating model object3");
  Model model3 = new Model("Self-Learn", "1.4");
  printObjectInfo(model3, fields);

 }
}




Previous                                                 Next                                                 Home

No comments:

Post a Comment