我正在开发一个具有培训课程的培训计划,该培训课程具有返回随机方法(一种锻炼类型)的函数。
这个通用类由一些特定类扩展,其中包含不同类型的练习。
然后我创建了一个特定类的数组,并想随机选择一个,然后调用随机练习方法。
这是通用类
public class TrainingClasses {
Method[] mMethods;
Random randomGenerator;
public void TraningClasses() {
randomGenerator = new Random();
/* Store methods */
mMethods= getClass().getDeclaredMethods();
}
public void RandomExercise() {
Random randGenerator = new Random();
int rnd = randGenerator.nextInt(mMethods.length);
mMethods[rnd].invoke(this);
}
这是特定培训课程的示例
public class MatheMagic extends TrainingClasses{
public MatheMagic() {
/*Something*/
}
public String[] SomeExercise() {
/*Some code */
}
public String[] SomeOtherExercise() {
/*Some code */
}
}
在主要活动的这一点上,我想这样做:
private Object[] mTrainingClasses;
private MatheMagic mMathMag;
/*eventually other training classes*/
mMathMag = new MatheMagic();
mTrainingClasses[0] = mMathMag;
Random randGenerator = new Random();
int rnd = randGenerator.nextInt(mTrainingClasses.length);
Object aTrain = mTrainingClasses[rnd];
/*Return exercise*/
String[] mRes = aTrain.RandomExercise();
这是代码的相关部分,现在仍然不完整......但是当我尝试存储动态调用方法的结果时,由于出现类型不匹配错误,我无法继续。很可能是项目结构不正确,我应该使用其他架构......但是,我还没有找到更好的主意。
感谢任何能够提供帮助的人。
–––––––––––––––––––––––––––––––––––––––––––––––––––––––––––</p >
谢谢你们的答案。这是可能需要的人的最终工作代码:
/** Common interface for all exercises */
public interface Exercise {
public String[] run();
}
/** Common interface for all training classes */
public abstract class TrainingClass {
private Random rand = new Random();
public ArrayList<Exercise> mExerciseTypes = new ArrayList<Exercise>();
/** Run a random exercise */
public String[] runRandomExercise() {
int i = rand.nextInt(mExerciseTypes.size());
return mExerciseTypes.get(i).run();
}
}
/*Specific training class*/
public class MatheMagic extends TrainingClass {
public MatheMagic() {
class SomeExercise implements Exercise {
public String[] run() {
String[] mRes = new String[2];
mRes[0] = "Question type 1";
mRes[1] = "Answer type 1";
return mRes;
}
}
class SomeOtherExercise implements Exercise {
public String[] run() {
String[] mRes = new String[2];
mRes[0] = "Question type 2";
mRes[1] = "Answer type 2";
return mRes;
}
}
SomeExercise mN = new SomeExercise();
SomeOtherExercise mS = new SomeOtherExercise();
mExerciseTypes.add(mN);
mExerciseTypes.add(mS);
}
}