Saturday 19 November 2022

Unset the properties of given type using reflection in Java

Implement a method, that takes an object and class as input, and set all the object properties of given type to null.

 

Signature

public static void unsetProperties(Object obj, final Class<?> clazz)

 

Find the below working application.


ReflectionUtil.java

package com.sample.util;

import java.lang.reflect.Field;

public class ReflectionUtil {

	/**
	 * Unset the properties of given class to null.
	 * 
	 * @param obj
	 * @param clazz
	 * 
	 * @throws IllegalArgumentException
	 * @throws IllegalAccessException
	 */
	public static void unsetProperties(Object obj, final Class<?> clazz)
			throws IllegalArgumentException, IllegalAccessException {

		if (clazz == null) {
			throw new IllegalArgumentException("clazz can't be null");
		}

		if (obj == null) {
			throw new IllegalArgumentException("obj can't be null");
		}

		final Field[] fields = obj.getClass().getDeclaredFields();

		for (Field field : fields) {
			field.setAccessible(true);

			if (field.getType().equals(clazz)) {
				field.set(obj, null);
			}

		}

	}

}

 

Employee.java

package com.sample.app.model;

public class Employee {

	private Integer id;
	private String name;
	private Double salary;

	public Employee(Integer id, String name, Double salary) {
		this.id = id;
		this.name = name;
		this.salary = salary;
	}

	public Integer getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

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

	public Double getSalary() {
		return salary;
	}

	public void setSalary(Double salary) {
		this.salary = salary;
	}

	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + ", salary=" + salary + "]";
	}

}

 

App.java

package com.sample.app;

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

public class App {

	public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
		Employee emp = new Employee(1, "Ram", 12345.678);

		System.out.println(emp);

		ReflectionUtil.unsetProperties(emp, String.class);
		System.out.println(emp);

	}

}

 

Output

Employee [id=1, name=Ram, salary=12345.678]
Employee [id=1, name=null, salary=12345.678]

 

 

 

Previous                                                 Next                                                 Home

No comments:

Post a Comment