java创建一个User类,属性有用户ID、用户名和密码,有一个show方法,读取配置文件User.properties的数据,利用反射调用指定类User中的show方法。
时间: 2024-03-23 20:41:43 浏览: 35
下面是一个示例代码:
```java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Properties;
public class User {
private String userId;
private String username;
private String password;
public User(String userId, String username, String password) {
this.userId = userId;
this.username = username;
this.password = password;
}
public void show() {
System.out.println("User ID: " + userId);
System.out.println("Username: " + username);
System.out.println("Password: " + password);
}
public static void main(String[] args) throws Exception {
Properties prop = new Properties();
InputStream input = new FileInputStream("User.properties");
prop.load(input);
input.close();
String userId = prop.getProperty("userId");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
User user = new User(userId, username, password);
Class<?> cls = user.getClass();
Method method = cls.getDeclaredMethod("show");
method.invoke(user);
}
}
```
在这个示例代码中,我们创建了一个User类,并在其中定义了属性和show方法。在main方法中,我们首先使用Properties类读取配置文件User.properties中的数据,然后创建一个User对象。接下来,我们通过调用getClass方法获取User对象的Class对象,然后使用getDeclaredMethod方法获取show方法的Method对象,最后使用invoke方法调用show方法。由于show方法是非静态方法,我们需要传递User对象作为invoke方法的第一个参数。