泛型方法+反射,解决静态可变类参数问题

问题描述:略

问题分析:略

具体代码如下:

Base是Lesson和Result的基类

public class Base {
	public static Base parse(String str) {
		return new Base();
	}
}

Lesson

public class Lesson extends Base{
	
	public static Lesson parse(String str){
		return new Lesson();
	}
}

Result

public class Result extends Base {

	public static Result parse(String str) {
		return new Result();
	}
}

BaseList是LessonList和ResultList的基类

public class BaseList {

    public static <BaseListT, BaseT> BaseListT parse(String str,
            Class<BaseListT> listClass, Class<BaseT> itemClass)

    throws SecurityException, NoSuchMethodException, IllegalArgumentException,
            IllegalAccessException, InvocationTargetException,
            InstantiationException {
        
        BaseListT baseList = (BaseListT) listClass.newInstance();

        List<BaseT> list = new ArrayList<BaseT>();

        Method method = itemClass.getMethod("parse",
                new Class[] { String.class });

        for (int i = 0; i < 10; i++) {
            BaseT base = (BaseT) method.invoke(itemClass, str);

            System.out.println(base.getClass().getName());

            list.add(base);
        }
        System.out.println(baseList.getClass().getName());

        return baseList;

    }
}

LessonList

public class LessonList extends BaseList {

	public static LessonList parse(String str) throws SecurityException,
			IllegalArgumentException, NoSuchMethodException,
			IllegalAccessException, InvocationTargetException, InstantiationException {
		
		return  (LessonList) BaseList.parse(str, LessonList.class,
				Lesson.class);
	}
}

ResultList

public class ResultList extends BaseList {

	public static ResultList parse(String str) throws SecurityException,
			IllegalArgumentException, NoSuchMethodException,
			IllegalAccessException, InvocationTargetException, InstantiationException {
		
		return (ResultList) BaseList.parse(str, ResultList.class,
				Result.class);

	}
}
Test类测试类

public class Test {

	public static void main(String args[]) throws SecurityException,
			IllegalArgumentException, NoSuchMethodException,
			IllegalAccessException, InvocationTargetException,
			InstantiationException {
		
		LessonList.parse("dfd");
		ResultList.parse("dfd");

	}
}



你可能感兴趣的:(泛型方法+反射,解决静态可变类参数问题)