Showing posts with label reflections. Show all posts
Showing posts with label reflections. Show all posts

Thursday, 18 May 2023

Utility class to get detailed information about the properties of a class

In this post, I am going to explain about an utility class that provide below functionalities with respect to a field.

 

a.   Check whether a field has getter and setter methods

b.   Check the information about field access modifiers like public, private, and protected

c.    Check whether the field is constant or not

d.   Check whether the field is readable or writeable

 

Find the below working application.

 


FieldInfoUtil.java

package com.sample.app.reflections.util;

public class FieldInfoUtil {
	
	public static String setterName(String fieldName) {
		int len = fieldName.length();
		int setterNameSize = len + 3;
		char[] b = new char[setterNameSize];
		b[0] = 's';
		b[1] = 'e';
		b[2] = 't';
		char propertyFirstChar = fieldName.charAt(0);
		propertyFirstChar = Character.toUpperCase(propertyFirstChar);
		b[3] = propertyFirstChar;
		for (int i = 1; i < len; i++) {
			b[i + 3] = fieldName.charAt(i);
		}
		return new String(b);
	}

	public static String getterName(String fieldName) {
		int len = fieldName.length();
		int getterNameSize = len + 3;
		char[] b = new char[getterNameSize];
		b[0] = 'g';
		b[1] = 'e';
		b[2] = 't';
		char propertyFirstChar = fieldName.charAt(0);
		propertyFirstChar = Character.toUpperCase(propertyFirstChar);
		b[3] = propertyFirstChar;
		for (int i = 1; i < len; i++) {
			b[i + 3] = fieldName.charAt(i);
		}
		return new String(b);
	}

	public static String getterNameForBoolean(String fieldName) {
		int len = fieldName.length();
		int getterNameSize = len + 2;
		char[] b = new char[getterNameSize];
		b[0] = 'i';
		b[1] = 's';
		char propertyFirstChar = fieldName.charAt(0);
		propertyFirstChar = Character.toUpperCase(propertyFirstChar);
		b[2] = propertyFirstChar;
		for (int i = 1; i < len; i++) {
			b[i + 2] = fieldName.charAt(i);
		}
		return new String(b);
	}
}

 

FieldInfo.java

package com.sample.app.model;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;

import com.sample.app.reflections.util.FieldInfoUtil;

public class FieldInfo {

	private Field field;

	private Method setter;

	private Method getter;

	private int index;

	private Class<?> type;

	private Type genericType;

	private FieldInfo() {

	}

	public int getIndex() {
		return index;
	}

	public boolean isEnum() {
		return type.isEnum();
	}

	public String getFieldName() {
		return field.getName();
	}

	public Class<?> getType() {
		return type;
	}

	public Type getGenericType() {
		return genericType;
	}

	public boolean isReadable() {
		return (getter != null || isPublicField());
	}

	public boolean isWritable() {
		if(isConstant()) {
			return false;
		}
		return (setter != null || isPublicField());
	}

	public Field getField() {
		return field;
	}

	public Method getSetter() {
		return setter;
	}

	public Method getGetter() {
		return getter;
	}

	public boolean isReadableAndWriteable() {
		return this.isReadable() && this.isWritable();
	}

	public boolean isPublicField() {
		int modifiers = field.getModifiers();
		return Modifier.isPublic(modifiers);
	}

	public boolean isPublicStaticField() {
		int modifiers = field.getModifiers();
		return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers);
	}

	public boolean isPrivateField() {
		int modifiers = field.getModifiers();
		return Modifier.isPrivate(modifiers);
	}

	public boolean isPrivateStaticField() {
		int modifiers = field.getModifiers();
		return Modifier.isPrivate(modifiers) && Modifier.isStatic(modifiers);
	}

	public boolean isProtectedField() {
		int modifiers = field.getModifiers();
		return Modifier.isProtected(modifiers);
	}

	public boolean isProtectedStaticField() {
		int modifiers = field.getModifiers();
		return Modifier.isProtected(modifiers) && Modifier.isStatic(modifiers);
	}

	public boolean isStaticField() {
		int modifiers = field.getModifiers();
		return Modifier.isStatic(modifiers);
	}

	public boolean isConstant() {
		int modifiers = field.getModifiers();
		return Modifier.isFinal(modifiers);
	}

	public boolean isStaticConstant() {
		int modifiers = field.getModifiers();
		return Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers);
	}

	public boolean isPublicStaticConstant() {
		int modifiers = field.getModifiers();
		return Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers);
	}

	public boolean isPrivateStaticConstant() {
		int modifiers = field.getModifiers();
		return Modifier.isPrivate(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers);
	}

	public boolean isProtectedStaticConstant() {
		int modifiers = field.getModifiers();
		return Modifier.isProtected(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers);
	}

	public static FieldInfo getFieldInfo(Class<?> clazz, Field field) {
		if (clazz == null) {
			throw new IllegalArgumentException("clazz is null");
		}

		if (field == null) {
			throw new IllegalArgumentException("field is null");
		}

		FieldInfo fieldInfo = new FieldInfo();

		fieldInfo.field = field;
		fieldInfo.type = field.getType();
		fieldInfo.genericType = field.getGenericType();

		if (fieldInfo.isStaticField()) {
			return fieldInfo;
		}

		String setterName = FieldInfoUtil.setterName(field.getName());
		try {
			fieldInfo.setter = clazz.getDeclaredMethod(setterName, field.getType());
		} catch (Exception e) {

		}

		boolean isBool = field.getType().equals(Boolean.TYPE);
		String getterName = null;
		if (isBool) {
			getterName = FieldInfoUtil.getterNameForBoolean(field.getName());
		} else {
			getterName = FieldInfoUtil.getterName(field.getName());
		}

		try {
			fieldInfo.getter = clazz.getDeclaredMethod(getterName);
		} catch (Exception e) {
		}

		return fieldInfo;
	}

}

 

FieldInfoDemo.java

package com.sample.app;

import java.lang.reflect.Field;

import com.sample.app.model.FieldInfo;

public class FieldInfoDemo {

    private static class DemoPojo {
        public final int P1 = 10;
        public static final double PI = 3.14;

        // Field with only setter method
        private int writeOnlyField;

        // Field with only getter method
        private int readOnlyField;

        // Field with both getter and setter methods
        private int readAndWriteableField;

        public void setWriteOnlyField(int writeOnlyField) {
            this.writeOnlyField = writeOnlyField;
        }

        public int getReadOnlyField() {
            return readOnlyField;
        }

        public int getReadAndWriteableField() {
            return readAndWriteableField;
        }

        public void setReadAndWriteableField(int readAndWriteableField) {
            this.readAndWriteableField = readAndWriteableField;
        }
    }

    private static void printFieldInfo(FieldInfo fieldInfo) {
        System.out.println("fieldName : " + fieldInfo.getFieldName());
        System.out.println("index : " + fieldInfo.getIndex());
        System.out.println("class : " + fieldInfo.getClass());
        System.out.println("field : " + fieldInfo.getField());
        System.out.println("generic type : " + fieldInfo.getGenericType());
        System.out.println("getter : " + fieldInfo.getGetter());
        System.out.println("setter : " + fieldInfo.getSetter());
        System.out.println("type : " + fieldInfo.getType());
        System.out.println("isConstant : " + fieldInfo.isConstant());
        System.out.println("isEnum : " + fieldInfo.isEnum());
        System.out.println("isPrivateField : " + fieldInfo.isPrivateField());
        System.out.println("isPrivateStaticConstant : " + fieldInfo.isPrivateStaticConstant());
        System.out.println("isPrivateStaticField : " + fieldInfo.isPrivateStaticField());
        System.out.println("isProtectedField : " + fieldInfo.isProtectedField());
        System.out.println("isProtectedStaticConstant : " + fieldInfo.isProtectedStaticConstant());
        System.out.println("isProtectedStaticField : " + fieldInfo.isProtectedStaticField());
        System.out.println("isPublicField : " + fieldInfo.isPublicField());
        System.out.println("isPublicStaticConstant : " + fieldInfo.isPublicStaticConstant());
        System.out.println("isPublicStaticField : " + fieldInfo.isPublicStaticField());
        System.out.println("isReadable : " + fieldInfo.isReadable());
        System.out.println("isReadableAndWriteable : " + fieldInfo.isReadableAndWriteable());
        System.out.println("isStaticConstant : " + fieldInfo.isStaticConstant());
        System.out.println("isStaticField : " + fieldInfo.isStaticField());
        System.out.println("isWritable : " + fieldInfo.isWritable());
        System.out.println("\n");
    }

    public static void main(String[] args) throws NoSuchFieldException, SecurityException {

        Field field1 = DemoPojo.class.getField("P1");
        Field field2 = DemoPojo.class.getField("PI");
        Field field3 = DemoPojo.class.getDeclaredField("writeOnlyField");
        Field field4 = DemoPojo.class.getDeclaredField("readOnlyField");
        Field field5 = DemoPojo.class.getDeclaredField("readAndWriteableField");

        printFieldInfo(FieldInfo.getFieldInfo(DemoPojo.class, field1));
        printFieldInfo(FieldInfo.getFieldInfo(DemoPojo.class, field2));
        printFieldInfo(FieldInfo.getFieldInfo(DemoPojo.class, field3));
        printFieldInfo(FieldInfo.getFieldInfo(DemoPojo.class, field4));
        printFieldInfo(FieldInfo.getFieldInfo(DemoPojo.class, field5));

    }

}

 

Output

fieldName : P1
index : 0
class : class com.sample.app.model.FieldInfo
field : public final int com.sample.app.FieldInfoDemo$DemoPojo.P1
generic type : int
getter : null
setter : null
type : int
isConstant : true
isEnum : false
isPrivateField : false
isPrivateStaticConstant : false
isPrivateStaticField : false
isProtectedField : false
isProtectedStaticConstant : false
isProtectedStaticField : false
isPublicField : true
isPublicStaticConstant : false
isPublicStaticField : false
isReadable : true
isReadableAndWriteable : false
isStaticConstant : false
isStaticField : false
isWritable : false


fieldName : PI
index : 0
class : class com.sample.app.model.FieldInfo
field : public static final double com.sample.app.FieldInfoDemo$DemoPojo.PI
generic type : double
getter : null
setter : null
type : double
isConstant : true
isEnum : false
isPrivateField : false
isPrivateStaticConstant : false
isPrivateStaticField : false
isProtectedField : false
isProtectedStaticConstant : false
isProtectedStaticField : false
isPublicField : true
isPublicStaticConstant : true
isPublicStaticField : true
isReadable : true
isReadableAndWriteable : false
isStaticConstant : true
isStaticField : true
isWritable : false


fieldName : writeOnlyField
index : 0
class : class com.sample.app.model.FieldInfo
field : private int com.sample.app.FieldInfoDemo$DemoPojo.writeOnlyField
generic type : int
getter : null
setter : public void com.sample.app.FieldInfoDemo$DemoPojo.setWriteOnlyField(int)
type : int
isConstant : false
isEnum : false
isPrivateField : true
isPrivateStaticConstant : false
isPrivateStaticField : false
isProtectedField : false
isProtectedStaticConstant : false
isProtectedStaticField : false
isPublicField : false
isPublicStaticConstant : false
isPublicStaticField : false
isReadable : false
isReadableAndWriteable : false
isStaticConstant : false
isStaticField : false
isWritable : true


fieldName : readOnlyField
index : 0
class : class com.sample.app.model.FieldInfo
field : private int com.sample.app.FieldInfoDemo$DemoPojo.readOnlyField
generic type : int
getter : public int com.sample.app.FieldInfoDemo$DemoPojo.getReadOnlyField()
setter : null
type : int
isConstant : false
isEnum : false
isPrivateField : true
isPrivateStaticConstant : false
isPrivateStaticField : false
isProtectedField : false
isProtectedStaticConstant : false
isProtectedStaticField : false
isPublicField : false
isPublicStaticConstant : false
isPublicStaticField : false
isReadable : true
isReadableAndWriteable : false
isStaticConstant : false
isStaticField : false
isWritable : false


fieldName : readAndWriteableField
index : 0
class : class com.sample.app.model.FieldInfo
field : private int com.sample.app.FieldInfoDemo$DemoPojo.readAndWriteableField
generic type : int
getter : public int com.sample.app.FieldInfoDemo$DemoPojo.getReadAndWriteableField()
setter : public void com.sample.app.FieldInfoDemo$DemoPojo.setReadAndWriteableField(int)
type : int
isConstant : false
isEnum : false
isPrivateField : true
isPrivateStaticConstant : false
isPrivateStaticField : false
isProtectedField : false
isProtectedStaticConstant : false
isProtectedStaticField : false
isPublicField : false
isPublicStaticConstant : false
isPublicStaticField : false
isReadable : true
isReadableAndWriteable : true
isStaticConstant : false
isStaticField : false
isWritable : true

 


Previous                                                 Next                                                 Home

Wednesday, 17 May 2023

Utility class to generate getter and setter methods for a class property

Java bean is a class that is adhere to following conventions.

a.  Private fields with corresponding getter and setter methods.

b.   Class must have a public no-argument constructor.

 

For example, below snippet defines a Person java bean with two properties (name, age).

public class Person {
    private String name;
    private int age;

    public Person() {
        // Default constructor
    }

    // Getter for the 'name' property
    public String getName() {
        return name;
    }

    // Setter for the 'name' property
    public void setName(String name) {
        this.name = name;
    }

    // Getter for the 'age' property
    public int getAge() {
        return age;
    }

    // Setter for the 'age' property
    public void setAge(int age) {
        this.age = age;
    }
}

 

According to the Java bean conventions, Person class mantains

a.   A public no-arg constructor

b.   Each property (name, age) has a getter and setter methods.

 

Naming convention for getter and setter methods

According to the Java naming conventions, getter methods begins with the prefix "get" while setter methods begin with "set", followed by the name of the corresponding variable. It is customary to capitalize the first letter of the variable name in both cases.

 

Example

getName()
setName(String name)

Above methods are related the the property ‘name’.

 

Getter and setter conventions for a boolean property

For a boolean property, getter methods begins with the prefix "is" while setter methods begin with "set", followed by the name of the corresponding variable. It is customary to capitalize the first letter of the variable name in both cases.

 

Example

isActive()
setActive(boolean active)

Following utility class takes a Java POJO as input and generate getter and setter methods for it.

 


GetterAndSetterUtil.java

package com.sample.app.reflections.util;

import java.lang.reflect.Field;

public class GetterAndSetterUtil {
    private static final String THREE_SPACES = "   ";
    
    public static String setterName(String fieldName) {
        int len = fieldName.length();
        int setterNameSize = len + 3;
        char[] b = new char[setterNameSize];
        b[0] = 's';
        b[1] = 'e';
        b[2] = 't';
        char propertyFirstChar = fieldName.charAt(0);
        propertyFirstChar = Character.toUpperCase(propertyFirstChar);
        b[3] = propertyFirstChar;
        for (int i = 1; i < len; i++) {
            b[i + 3] = fieldName.charAt(i);
        }
        return new String(b);
    }

    public static String getterName(String fieldName) {
        int len = fieldName.length();
        int getterNameSize = len + 3;
        char[] b = new char[getterNameSize];
        b[0] = 'g';
        b[1] = 'e';
        b[2] = 't';
        char propertyFirstChar = fieldName.charAt(0);
        propertyFirstChar = Character.toUpperCase(propertyFirstChar);
        b[3] = propertyFirstChar;
        for (int i = 1; i < len; i++) {
            b[i + 3] = fieldName.charAt(i);
        }
        return new String(b);
    }

    public static String getterNameForBoolean(String fieldName) {
        int len = fieldName.length();
        int getterNameSize = len + 2;
        char[] b = new char[getterNameSize];
        b[0] = 'i';
        b[1] = 's';
        char propertyFirstChar = fieldName.charAt(0);
        propertyFirstChar = Character.toUpperCase(propertyFirstChar);
        b[2] = propertyFirstChar;
        for (int i = 1; i < len; i++) {
            b[i + 2] = fieldName.charAt(i);
        }
        return new String(b);
    }

    public static String getterCode(Field field) {
        boolean isBool = field.getType().equals(Boolean.TYPE);
        StringBuilder builder = new StringBuilder();
        builder.append("public").append(" ");
        if (isBool) {
            builder.append("Boolean").append(" ");
            builder.append(getterNameForBoolean(field.getName()));

        } else {
            builder.append(field.getType().getSimpleName()).append(" ");
            builder.append(getterName(field.getName()));
        }

        builder.append("()");
        builder.append("{\n").append(THREE_SPACES).append("return this.").append(field.getName()).append(";\n}");
        return builder.toString();
    }

    public static String setterCode(Field field) {
        StringBuilder builder = new StringBuilder();
        builder.append("public").append(" ").append("void").append(" ");
        builder.append(setterName(field.getName()));
        builder.append("(");
        builder.append(field.getType().getSimpleName());
        builder.append(" ");
        builder.append(field.getName());
        builder.append(")");

        builder.append("{\n").append(THREE_SPACES).append("this.").append(field.getName());
        builder.append("=").append(field.getName()).append(";\n}");
        return builder.toString();
    }

    public static void printGettersAndSetters(Class<?> clazz) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            System.out.println();
            System.out.println(getterCode(field));
            System.out.println(setterCode(field));
        }
    }

}

GetterAndSetterUtilDemo.java

package com.sample.app.reflections.util;

public class GetterAndSetterUtilDemo {

    private static class Person {
        private String name;
        private int age;
        private boolean activeUser;

    }
    
    public static void main(String[] args) {
        GetterAndSetterUtil.printGettersAndSetters(Person.class);
    }
}

Output

public String getName(){
   return this.name;
}
public void setName(String name){
   this.name=name;
}

public int getAge(){
   return this.age;
}
public void setAge(int age){
   this.age=age;
}

public Boolean isActiveUser(){
   return this.activeUser;
}
public void setActiveUser(boolean activeUser){
   this.activeUser=activeUser;
}

 

Previous                                                 Next                                                 Home

Tuesday, 9 May 2023

Utility class to work with reflections in Java

In this post, I am going to explain about an utility class to made your work easier while working with reflections.

 

Utility class provide below methods.

a.   Get an instance of an object

b.   Invoke an instance method with or without arguments

c.    Invoke static method with or without arguments

d.   Get the value of instance property

e.   Set the value to an instance property

f.     Check for the existence of given method name


Get an instance of an object

public static Object newInstance(String classFullName) throws Throwable {
	try {
		Class<?> clazz = Class.forName(classFullName, true, ReflectionUtil.class.getClassLoader());
		Constructor<?> constructor = clazz.getConstructor();
		return constructor.newInstance();
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T newInstance(Class<T> ofClass, Class<?>[] argTypes, Object[] args) throws Throwable {
	try {
		Constructor<T> con = ofClass.getConstructor(argTypes);
		return con.newInstance(args);
	} catch (Throwable t) {
		throw t;
	}
}

 

Invoke an instance method with or without arguments

public static <T> T invokeMethod(Object obj, String methodName) throws Throwable {
	try {
		Method method = obj.getClass().getMethod(methodName);
		return (T) method.invoke(obj);
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T invokeMethod(Object obj, String methodName, Class<?> argType, Object arg) throws Throwable {
	try {
		Method method = obj.getClass().getMethod(methodName, argType);
		return (T) method.invoke(obj, arg);
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T invokeMethod(Object obj, String methodName, Class<?> argType1, Object arg1, Class<?> argType2,
		Object arg2) throws Throwable {
	try {
		Method method = obj.getClass().getMethod(methodName, argType1, argType2);
		return (T) method.invoke(obj, arg1, arg2);
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T invokeMethod(Object obj, String methodName, Class<?>[] argTypes, Object[] args)
		throws Throwable {
	try {
		Method method = obj.getClass().getMethod(methodName, argTypes);
		return (T) method.invoke(obj, args);
	} catch (Throwable t) {
		throw t;
	}
}

 

c. Invoke static method with or without arguments

public static <T> T invokeStaticMethod(Class<?> clazz, String methodName) throws Throwable {
	try {
		Method method = clazz.getDeclaredMethod(methodName);
		return (T) method.invoke(null);
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?> argType, Object arg)
		throws Throwable {
	try {
		Method method = clazz.getDeclaredMethod(methodName, argType);
		return (T) method.invoke(null, arg);
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?> argType1, Object arg1,
		Class<?> argType2, Object arg2) throws Throwable {
	try {
		Method method = clazz.getDeclaredMethod(methodName, argType1, argType2);
		return (T) method.invoke(null, arg1, arg2);
	} catch (Throwable t) {
		throw t;
	}
}

public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?>[] argTypes, Object[] args)
		throws Throwable {
	try {
		Method method = clazz.getDeclaredMethod(methodName, argTypes);
		return (T) method.invoke(null, args);
	} catch (Throwable t) {
		throw t;
	}
}

 

Get the value of instance property

public static <T> T getField(Object obj, String fieldName) throws Throwable {
	try {
		Field field = obj.getClass().getDeclaredField(fieldName);
		field.setAccessible(true);
		return (T) field.get(obj);
	} catch (Throwable t) {
		throw t;
	}
}

 

Set the value to an instance property

public static void setField(Object obj, String fieldName, Object value) throws Throwable {
	try {
		Field field = obj.getClass().getDeclaredField(fieldName);
		field.setAccessible(true);
		field.set(obj, value);
	} catch (Throwable t) {
		throw t;
	}
}

 

Check for existence of given method name

public static boolean isMethodExists(Object o, String methodName) {
	try {
		return Stream.of(o.getClass().getDeclaredMethods()).map(Method::getName)
				.anyMatch(Predicate.isEqual(methodName));
	} catch (Throwable t) {
		throw t;
	}
}

 

Find the below working application.

 

Employee.java

 

package com.sample.app.model;

import java.util.List;

public class Employee {

	private int id;
	private String name;
	private int age;

	public Employee() {}

	public Employee(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}
	
	public void updateDetails(int id, String name, int age) {
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	public static Employee olderEmployee(List<Employee> emps) {
		if(emps == null || emps.isEmpty()) {
			return null;
		}
		
		Employee maxAgeEmp = new Employee(-1,"", -1);
		for(Employee emp: emps) {
			if(emp.age > maxAgeEmp.age) {
				maxAgeEmp = emp;
			}
		}
		
		return maxAgeEmp;
	}
	
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

 

ReflectionUtil.java

package com.sample.app.reflections.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.function.Predicate;
import java.util.stream.Stream;

public class ReflectionUtil {

	public static Object newInstance(String classFullName) throws Throwable {
		try {
			Class<?> clazz = Class.forName(classFullName, true, ReflectionUtil.class.getClassLoader());
			Constructor<?> constructor = clazz.getConstructor();
			return constructor.newInstance();
		} catch (Throwable t) {
			throw t;
		}
	}

	public static <T> T newInstance(Class<T> ofClass, Class<?>[] argTypes, Object[] args) throws Throwable {
		try {
			Constructor<T> con = ofClass.getConstructor(argTypes);
			return con.newInstance(args);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeMethod(Object obj, String methodName) throws Throwable {
		try {
			Method method = obj.getClass().getMethod(methodName);

			// this is required to access private methods too
			method.setAccessible(true);
			return (T) method.invoke(obj);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeMethod(Object obj, String methodName, Class<?> argType, Object arg) throws Throwable {
		try {
			Method method = obj.getClass().getMethod(methodName, argType);
			method.setAccessible(true);
			return (T) method.invoke(obj, arg);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeMethod(Object obj, String methodName, Class<?> argType1, Object arg1, Class<?> argType2,
			Object arg2) throws Throwable {
		try {
			Method method = obj.getClass().getMethod(methodName, argType1, argType2);
			method.setAccessible(true);
			return (T) method.invoke(obj, arg1, arg2);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeMethod(Object obj, String methodName, Class<?>[] argTypes, Object[] args)
			throws Throwable {
		try {
			Method method = obj.getClass().getMethod(methodName, argTypes);
			method.setAccessible(true);
			return (T) method.invoke(obj, args);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeStaticMethod(Class<?> clazz, String methodName) throws Throwable {
		try {
			Method method = clazz.getDeclaredMethod(methodName);
			method.setAccessible(true);
			return (T) method.invoke(null);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?> argType, Object arg)
			throws Throwable {
		try {
			Method method = clazz.getDeclaredMethod(methodName, argType);
			method.setAccessible(true);
			return (T) method.invoke(null, arg);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?> argType1, Object arg1,
			Class<?> argType2, Object arg2) throws Throwable {
		try {
			Method method = clazz.getDeclaredMethod(methodName, argType1, argType2);
			method.setAccessible(true);
			return (T) method.invoke(null, arg1, arg2);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T invokeStaticMethod(Class<?> clazz, String methodName, Class<?>[] argTypes, Object[] args)
			throws Throwable {
		try {
			Method method = clazz.getDeclaredMethod(methodName, argTypes);
			method.setAccessible(true);
			return (T) method.invoke(null, args);
		} catch (Throwable t) {
			throw t;
		}
	}

	@SuppressWarnings("unchecked")
	public static <T> T getField(Object obj, String fieldName) throws Throwable {
		try {
			Field field = obj.getClass().getDeclaredField(fieldName);
			field.setAccessible(true);
			return (T) field.get(obj);
		} catch (Throwable t) {
			throw t;
		}
	}

	public static void setField(Object obj, String fieldName, Object value) throws Throwable {
		try {
			Field field = obj.getClass().getDeclaredField(fieldName);
			field.setAccessible(true);
			field.set(obj, value);
		} catch (Throwable t) {
			throw t;
		}
	}

	public static boolean isMethodExists(Object o, String methodName) {
		try {
			return Stream.of(o.getClass().getDeclaredMethods()).map(Method::getName)
					.anyMatch(Predicate.isEqual(methodName));
		} catch (Throwable t) {
			throw t;
		}
	}

}

ReflectionUtilDemo.java

package com.sample.app;

import java.util.Arrays;
import java.util.List;

import com.sample.app.model.Employee;
import com.sample.app.reflections.util.ReflectionUtil;

public interface ReflectionUtilDemo {

	private static void newInstanceTest() throws Throwable {
		System.out.println("newInstanceTest example");
		Employee emp1 = (Employee) ReflectionUtil.newInstance("com.sample.app.model.Employee");

		Class<?>[] argTypes = { int.class, String.class, int.class };
		Object[] args = { 1, "Krishna", 34 };
		Employee emp2 = ReflectionUtil.newInstance(Employee.class, argTypes, args);

		System.out.println("emp1 : " + emp1);
		System.out.println("emp2 : " + emp2);
	}

	private static void invokeMethodTest() throws Throwable {
		System.out.println("\ninvokeMethodTest example");
		Employee emp1 = (Employee) ReflectionUtil.newInstance("com.sample.app.model.Employee");

		ReflectionUtil.invokeMethod(emp1, "setName", String.class, "Krishna");
		ReflectionUtil.invokeMethod(emp1, "setId", int.class, 1);
		ReflectionUtil.invokeMethod(emp1, "setAge", int.class, 35);

		System.out.println(emp1);

		Class<?>[] argTypes = { int.class, String.class, int.class };
		Object[] args = { 2, "Ram", 36 };
		ReflectionUtil.invokeMethod(emp1, "updateDetails", argTypes, args);
		System.out.println(emp1);
	}

	private static void invokeStaticMethodTest() throws Throwable {
		System.out.println("\ninvokeStaticMethodTest example");
		Employee emp1 = new Employee(1, "Krishna", 34);
		Employee emp2 = new Employee(2, "Sailu", 35);
		Employee emp3 = new Employee(3, "Bala", 41);
		Employee emp4 = new Employee(4, "Loopa", 26);

		List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4);

		Employee olderEmployee = ReflectionUtil.invokeStaticMethod(Employee.class, "olderEmployee", List.class, emps);
		System.out.println(olderEmployee);
	}

	private static void getFieldTest() throws Throwable {
		System.out.println("\ngetFieldTest example");
		Employee emp1 = new Employee(1, "Krishna", 34);

		int id = (int) ReflectionUtil.getField(emp1, "id");
		String name = (String) ReflectionUtil.getField(emp1, "name");
		int age = (int) ReflectionUtil.getField(emp1, "age");

		System.out.println("id : " + id);
		System.out.println("name : " + name);
		System.out.println("age : " + age);

	}

	private static void setFieldTest() throws Throwable {
		System.out.println("\nsetFieldTest example");
		Employee emp1 = new Employee();

		ReflectionUtil.setField(emp1, "id", 1);
		ReflectionUtil.setField(emp1, "name", "Krishna");
		ReflectionUtil.setField(emp1, "age", 34);

		System.out.println(emp1);
	}

	private static void isMethodExistsTest() {
		System.out.println("\nisMethodExistsTest example");
		Employee emp1 = new Employee();

		boolean isSetIdExists = ReflectionUtil.isMethodExists(emp1, "setId");
		boolean isOlderEmployeeExists = ReflectionUtil.isMethodExists(emp1, "olderEmployee");
		boolean isSetABCExists = ReflectionUtil.isMethodExists(emp1, "setABC");

		System.out.println("setId exists : " + isSetIdExists);
		System.out.println("olderEmployee exists : " + isOlderEmployeeExists);
		System.out.println("setABC exists : " + isSetABCExists);
	}

	public static void main(String[] args) throws Throwable {
		newInstanceTest();

		invokeMethodTest();

		invokeStaticMethodTest();

		getFieldTest();

		setFieldTest();

		isMethodExistsTest();
	}

}

Output

newInstanceTest example
emp1 : Employee [id=0, name=null, age=0]
emp2 : Employee [id=1, name=Krishna, age=34]

invokeMethodTest example
Employee [id=1, name=Krishna, age=35]
Employee [id=2, name=Ram, age=36]

invokeStaticMethodTest example
Employee [id=3, name=Bala, age=41]

getFieldTest example
id : 1
name : Krishna
age : 34

setFieldTest example
Employee [id=1, name=Krishna, age=34]

isMethodExistsTest example
setId exists : true
olderEmployee exists : true
setABC exists : false


 

Previous                                                 Next                                                 Home