Java 我们可以将字符串转换为函数名并调用该函数吗?
Student.javaJava 我们可以将字符串转换为函数名并调用该函数吗?,java,string,function,Java,String,Function,Student.java class Student { String name; String address; } 我们有名字和地址的getter和setter。 现在,如果我们想基于一些变量调用函数,比如: Demo.java class Demo { Student s = new Student(); String var = "name"; } 现在,如果我想根据分配给var的值调用getName或getAddress,我该如何
class Student {
String name;
String address;
}
我们有名字和地址的getter和setter。
现在,如果我们想基于一些变量调用函数,比如:
Demo.java
class Demo {
Student s = new Student();
String var = "name";
}
现在,如果我想根据分配给var的值调用
getName
或getAddress
,我该如何实现它呢?您要寻找的是反射。下面是调用getter和setter的一个非常简单的示例,代码中有更多解释
为简单起见,这是学生班
class Student {
String name;
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
}
这就是如何调用getter和setter
try {
Student student = new Student();
String propertyName = "name";
//creates setName from "set" and "name"
String setterName = "set" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
// we are looking for method with name setterName which has one String argument
Method setter = student.getClass().getMethod(setterName, String.class);
//call setName, pass Bob as an argument
setter.invoke(student, "Bob");
//creates setName from "get" and "name"
String getterName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
//we are looking for method with name getterName having no input arguments
Method getter = student.getClass().getMethod(getterName);
//calls getter, gets Bob
String retrievedName = getter.invoke(student).toString();
System.out.println("Hello " + retrievedName + "!");
//String is the method argument type
} catch (Exception e) {
throw new RuntimeException(e);
}
您可以使用反射来获取字段值,如下所示:
Student S = new Student();
String var = "name";
try {
Object value = S.getClass().getDeclaredField(var).get(S);
System.out.println(value);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
e.printStackTrace();
}
如果您无法访问该字段或指定的字段不存在,则会抛出一些异常,并执行catch部分。您可以编写switch语句,也可以使用。此外,您可以使用
Student.class
而不是S.getclass()