您需要使用Reflection。不久前,我 wrote 一些 JSTL 标记实用程序可以执行此类操作。一个函数检查一个类是否是传入字符串的实例(基本上是instanceof)。另一个检查一个类是否具有指定的属性 (hasProperty)。以下代码 sn-p 应该会有所帮助:
//Checks to see if Object 'o' is an instance of the class in the string "className"
public static boolean instanceOf(Object o, String className) {
boolean returnValue;
try {
returnValue = Class.forName(className).isInstance(o);
}
catch(ClassNotFoundException e) {
returnValue = false;
}
return returnValue;
}
//Checks to see if Object 'o' has a property specified in "propertyName"
public static boolean hasProperty(Object o, String propertyName) {
boolean methodFound = false;
int i = 0;
Class myClass = o.getClass();
String methodName = "get" + propertyName.toUpperCase().charAt(0) + propertyName.substring(1);
Method[] methods = myClass.getMethods();
while(i < methods.length && !methodFound) {
methodFound = methods[i].getName().compareTo(methodName) == 0;
i++;
}
return methodFound;
}
特别注意第一个方法(加载和初始化一个类)中的Class.forName 方法和第二个函数中的getMethods() 方法,它返回为一个类定义的所有方法。
你可能想要的是Class.forName,它也初始化了这个类。之后,您可以使用newInstance 获取该类的新实例(如果需要)。要访问这些字段,您需要使用从getMethod() 获得的Method 对象。对这些对象使用invoke 方法。如果这些方法是 getter 方法,那么您现在可以访问所需的字段。
编辑
查看您问题中的代码后,我意识到您需要这些属性的 getter 和 setter。因此,假设您定义了 getABC 和 getXYZ,这里有一个有些人为的例子:
public Object reflectionDemo(String className, String getter) throws ClassNotFoundException, NoSuchMethodException {
Object fieldValue;
Class myClass = Class.forName(className);
Object myClassInstance = myClass.newInstance(); //to get an instance of the class
if(myClassInstance instanceof My_Class_X123) {
//null because we are not specifying the kind of arguments that class takes
Method getterMethod = myClass.getMethod(getter, null);
//null because the method takes no arguments
//Also in the scenario that the method is static one, it is not necessary to pass in an instance, so in that case, the first parameter can be null.
fieldValue = getterMethod.invoke(myClassInstance, null);
}
return fieldValue;
}
上述方法更通用。如果您只想要这些字段,那么您可以使用 James 描述的方法:
myClass = null;
try {
myClass = Class.forName(className);
Field[] fields = myClass.getDeclaredFields();
for(Field field : fields) {
//do whatever with the field. Look at the API reference at http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html
}
}
catch(Exception e) {
//handle exception
}