How can I get a particular method name as string instead of hardcoding a method name

Gangadhar Enagandula :

I have to call a particular method through Java reflection. Instead of passing hardcoded method name, is it possible to pass the method name as a string?

For example

 public String getAttribute(Object object1, Object2, String className, String methodName){
     Class<?> clazz = Class.forName(className);
     Method method = clazz.getMethod(methodName);
     return ObjectUtils.firstNonNull(null == object1 ? null: method.invoke(object1),null == object2 ? null: method.invoke(object2); }

Let us say I have a class

 @Getter
 @Setter 
 Class Student{
   String studentName;
   String address;
   int rollNumber;
 }

Lets say, we have caller code

Student student1 = new Student();// Student record from School 1
Student student2 = new Student(); // Student record from School 2
student2.setAddress("ABC");
System.out.println(getAttribute(student1, student2, Student.class.name(), "getAddress"));

Instead of passing hardcoded method name as parameter to getAttribute() method, is there a way that I can use a method name that is not hardcoded?

For example, getAttribute(student, Student.class.name(), Student.class.getStudentName.getName()) so that we can easily make the changes to methods and variable of the student class when required without worrying on hardcoded method name constants.

FThompson :

To find the first non-null result of a given getter of the objects in a collection, you could utilize streams, method references, and optionals, while avoiding reflection entirely.

public static <T, R> Optional<R> findFirstNonNull(Collection<T> objects, 
                                                  Function<T, R> getter) {
    return objects.stream()
            .filter(Objects::nonNull)
            .map(getter)
            .filter(Objects::nonNull)
            .findFirst();
}

Example usage: Optional<String> found = findFirstNonNull(fooList, Foo::getName);

public class Foo {

    private String name;

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

    public String getName() {
        return name;
    }

    public static void main(String[] args) {
        Foo foo1 = null;
        Foo foo2 = new Foo();
        Foo foo3 = new Foo();
        foo3.setName("foo3");
        Foo foo4 = new Foo();
        foo4.setName("foo4");
        List<Foo> fooList = Arrays.asList(foo1, foo2, foo3, foo4);
        Optional<String> found = findFirstNonNull(fooList, Foo::getName);
        System.out.println(found); // Optional[foo3]
    }
}

Note: these are Java 8 features.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=91217&siteId=1