lundi 4 avril 2016

Java Reflection - get method without specific parameters type

I am trying to get the method by java reflection, but i don't want to be specific about the parameters classes in getMethod().

public Object prepareFilter(String filter, String sort) {
    Class filterClass = this.filterClass;
    try {
        Method createCriteriaMethod = filterClass.getMethod(CREATE_CRITERIA_METHOD);
        Method orderByClauseMethod = filterClass.getMethod(ORDER_BY_CLAUSE_METHOD, String.class);

        Class criteriaClass = createCriteriaMethod.getReturnType();

        Object filterObject = filterClass.newInstance();
        Object criteriaObject = createCriteriaMethod.invoke(filterObject);

        for (ExtFilterRequest extFilter : ExtFilterRequest.decodeJson(filter)) {
            StringBuilder sb = new StringBuilder()
                                    .append(AND)
                                    .append(WordUtils.capitalize(extFilter.getProperty()))
                                    .append(extFilter.getCondition());
            Method criteriaConditionMethod = criteriaClass.getMethod(sb.toString(), ????); // earlier extFilter.getTransformedValue().getClass()
            criteriaConditionMethod.invoke(criteriaObject, extFilter.getTransformedValue());
        }

        String orderByClause = ExtSortRequest.getOrderByString(sort);
        if (orderByClause != null)
            orderByClauseMethod.invoke(filterObject, orderByClause);

        return filterObject;

    } catch (Exception e) {
        // later
    }

    return null;
}

I have the methods generated by MyBatis and I want to call them by reflection with the decoded json that comes from extjs client. It looks like: operator, value and property. Following code is working with string values but i dont know what to put in the place of question marks when I call for example method which get a Date value (decoded value is always a string).

Is it possible to call getMethod with some hmm.. generic type and get the specific method? Or should I do it in another way?

Summarizing - if I have method like this:

public Criteria andSomeReferenceIsEqualTo(String value) {
        addCriterion("some_ref =", value, "someRef");
        return (Criteria) this;
}

and this

public Criteria andPrimDateEqualTo(Date value) {
        addCriterionForJDBCDate("prim_date =", value, "primDate");
        return (Criteria) this;
}

I want to call them in the same way by method I specify earlier - even if its boolean, list of values, string or integer.





Aucun commentaire:

Enregistrer un commentaire