Java-使用动态名称变量访问类方法
这个问题我已经有一段时间了,直到现在我才设法避免它。基本上我有一个类,它存储高尔夫球场每个洞的信息,并有一个getter返回这些信息。在另一个类中,当用户从孔1移动到孔2(当前存储为整数)时,我希望访问孔2的getter方法,但不知道如何实现 代码: 课程信息类:Java-使用动态名称变量访问类方法,java,class,dynamic-programming,static-methods,Java,Class,Dynamic Programming,Static Methods,这个问题我已经有一段时间了,直到现在我才设法避免它。基本上我有一个类,它存储高尔夫球场每个洞的信息,并有一个getter返回这些信息。在另一个类中,当用户从孔1移动到孔2(当前存储为整数)时,我希望访问孔2的getter方法,但不知道如何实现 代码: 课程信息类: //Hole information private static String[] hole1 = {"name", "Distance", "Par"}; private static String[] hole2 = {"nam
//Hole information
private static String[] hole1 = {"name", "Distance", "Par"};
private static String[] hole2 = {"name", "Distance", "Par"};
public static String[] getHole1(){
return hole1;
}
public static String[] getHole2(){
return hole2;
}
主要类别:
String[] holeInfo;
int currentHole = 1;
//How I call hole1 info just now
//I just access the elements of the array as needed then
holeCoOrds = course.getHole1();
//User starts next hole (this will be the case for all 18 holes)
currentHole++
//Call next hole information getter method here
//Something along the lines of;
holeCoOrds = course.getHole(currentHole)();
任何帮助都会被感激的,我绞尽脑汁已经有一段时间了,但没有成功
提前感谢。您没有最好的方法:
//Hole information
private static String[] hole1 = {"name", "Distance", "Par"};
private static String[] hole2 = {"name", "Distance", "Par"};
可以通过以下方式存储在列表中:
private static List<String[]> holes = new ArrayList<String[]>();
private static String[] hole1 = {"name", "Distance", "Par"};
holes.add(hole1);
private static String[] hole2 = {"name", "Distance", "Par"};
holes.add(hole2);
如果希望更好地控制孔,请使用贴图添加标识每个孔值的关键点:
你可以通过反射来做到这一点。但是,更好的方法是重新设计类,这样就没有必要了。将所有hole
数组放入另一个数组或列表中,然后创建一个getHole(int)
方法,从中返回一个项
因此,一个简单的(没有健全性检查)版本如下所示:
private static String[] holes = {{"name", "Distance", "Par"},
{"name", "Distance", "Par"}};
public static String[] getHole(int hole){
return holes[hole];
}
这使得以后可以很容易地添加额外的孔,并使您的代码更加灵活,这样您就不需要在编译时知道需要哪个孔了。为什么不为孔
实体创建一个类,如下所示:
public class Hole {
private int holeNo;
private String name;
private String dist;
private String par;
//getters and setters for above properties
}
因此,当您从主类调用代码时,很容易穿过一组孔(2个或更多)
您甚至可以将孔对象的所有实例保留在地图中,以便轻松检索。我不敢相信我没有想到这一点,等待期过后将设置为接受答案。再次感谢:)
public static String[] getHole(int holeNumber){
return holes.get(holeNumber);
}
private static String[] holes = {{"name", "Distance", "Par"},
{"name", "Distance", "Par"}};
public static String[] getHole(int hole){
return holes[hole];
}
public class Hole {
private int holeNo;
private String name;
private String dist;
private String par;
//getters and setters for above properties
}