marți, 2 iunie 2015

[OmniFaces utilities 2.3/2.0] Find a method using base, method name and amount of parameters


[OmniFaces utilities] The findMethod() finds a method based on the method name, amount of parameters and limited typing, if necessary prefixed with "get". Note that this supports overloading, but a limited one. Given an actual parameter of type Long, this will select a method accepting Number when the choice is between Number and a non-compatible type like String. However, it will NOT select the best match if the choice is between Number and Long.

Starting withOmniFaces 2.3 this method was improve to find superclass private methods too.

Method:
OmniFaces 2.3OmniFaces 2.0
Usage:

Let's suppose that we have a simple bean (BookBean) that contains the below two methods:

public void addNewBook(String name, Long isbn, Double price){
 // ...
}
   
public void addNewBook(String name, String isbn, String price){
 // ...
}

Now, let's see three examples of finding these methods using Reflection#findMethod():

import org.omnifaces.util.Reflection;
...
Object[] paramsA={"", 0L, 0d};
Object[] paramsB={"", "0", "0"};
Object[] paramsC={"", 0, 0};

BookBean bookBean = new BookBean();

// finds: public void book.beans.BookBean.addNewBook(java.lang.String,java.lang.Long,java.lang.Double)
Method methodA = Reflection.findMethod(bookBean, "addNewBook", paramsA);
// finds: public void book.beans.BookBean.addNewBook(java.lang.String,java.lang.String,java.lang.String)
Method methodB = Reflection.findMethod(bookBean, "addNewBook", paramsB);
// finds: null
Method methodC = Reflection.findMethod(bookBean, "addNewBook", paramsC);

Niciun comentariu:

Trimiteți un comentariu