第一次Java,第一次反射

对Java不熟悉,如果要用PHP/Python之类来做,下面代码用不到这么复杂吧。过则不美,用了后悔。

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package others.commons.play;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import play.db.jpa.GenericModel.JPAQuery;

/**
 *
 * @author Administrator
 */
public class Paginator {
    public List data;
    public int page;
    public int pageSize = 10;
    public int pageCount;
    public String css;

    public Paginator(Class<? extends Model> aClass, long page, long pageSize, String css){
        this.page = (int)page;
        this.pageSize = (int)pageSize;
        this.css = css;
        this.pageCount = (int)count(aClass);
        this.data = getData(aClass, (int)page, (int)pageSize);
    }

    public String indicator() {
        return "html here";
    }

    private static List getData(Class<? extends Model> typeToken, int p1, int p2) {
        Method method;
        JPAQuery handle;
        try {
            method = typeToken.getMethod("all");
            handle = (JPAQuery) method.invoke(typeToken);
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }

        //

        return handle.fetch(p1, p2);
    }
    private static long count(Class<? extends Model> typeToken) {
        Method method;
        Long count = new Long(0);
        try {
            method = typeToken.getMethod("count");     // 实在想不明白直接调用一下有什么问题
            count = (Long) method.invoke(typeToken);   // 这里需要invoke个鸟~~~~
        } catch (IllegalArgumentException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (SecurityException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
        return count.longValue();

    }

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注