Monday, August 13, 2018

Read/Fetch/Print only getter methods of any class with Introspector and PropertyDescriptor

Through reflection we can read any property of java class but its difficult to fetch only required methods.

I found one new way to do it.

please follow below mentioned example and run it

Step 1: Create Employee.java

public class Employee implements java.io.Serializable{
private int id;
private String name;

public Employee(){}

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

public int getId(){return id;}

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

public String getName(){return name;}

}

Step 2: Create HelloWorldRef

import java.beans.Introspector;
import java.beans.PropertyDescriptor;

public class HelloWorldRef {
public static void main(String[] args) {
System.out.println("Hello World!"); // Display the string.
try {
for(PropertyDescriptor propertyDescriptor :
Introspector.getBeanInfo(Employee.class,Object.class).getPropertyDescriptors()){

// propertyEditor.getReadMethod() exposes the getter
// btw, this may be null if you have a write-only property
System.out.println(propertyDescriptor.getReadMethod());
}
}catch(Exception e){
e.printStackTrace();
}
}
}

Step 3:Run HelloWorldRef class

you will get below output

Hello World!
public int com.technical.examples.Docker.Employee.getId()
public java.lang.String com.technical.examples.Docker.Employee.getName()

Here we got just getter methods from employee class.

No comments:

Post a Comment

How to check whether operating system is 64 bit or 32bit?

What is 32 and 64 bit operating system? The terms 32-bit and 64-bit refer to the way a computer's processor that is CPU, handles info...