运行结果:
XML file info: [ user =root , password =123456]
property_name: User
property_value: root
property_name: Password
property_value: 123456
Instance: ConstructorTest [user=root, password=123456]
property_name: User
property_value: root
property_name: Password
property_value: 123456
Instance: ConstructorTest [user=root, password=123456]
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 该程序模拟框架中利用XML文件创建对象的机制;创建指定对象;其原理在于先从XML文件读入到String
* 中,再通过Regex读取类的必要信息;创建实例对象;
* @author crf
*
*/
public class ConstructorTest {
public static void main(String[] args) {
String xml = "< user =root >< password =123456>"; //模拟读取的xml文件中的内容;
String regex ="<(.+?)>"; //正则表达式;
Class<?> clazz = null; //初始化需要加载的类和实例;
Object instance =null;
try { //获得类,并利用无参构造器创建实例;
clazz = Class.forName("reflexTest.ConstructorTest");
instance = clazz.getConstructor().newInstance();
} catch (Exception e) {
e.printStackTrace();
}
Matcher m = Pattern.compile(regex).matcher(xml); //抽取xml中的信息;
ArrayList<String> strs = new ArrayList<String>();
while(m.find()){
strs.add(m.group(1));
}
System.out.println("XML file info: "+strs);
for (String string : strs) { //依次获得属性名称和值;
String RE = "^\\s*(\\w*)\\s*=\\s*(\\w*)\\s*$";
Matcher matcher = Pattern.compile(RE).matcher(string);
while(matcher.find()){
String property_name = matcher.group(1);
String property_val = matcher.group(2);
//切换首字母大小写;
property_name=property_name.replace(property_name.substring(0,1),
property_name.substring(0,1).toUpperCase());
System.out.println("property_name: "+property_name);
System.out.println("property_value: "+property_val);
String method_name = "set"+property_name; //拼接出方法名称;
try { //调用set方法;
clazz.getMethod(method_name, String.class).invoke(instance, property_val);
} catch (Exception e) {
e.printStackTrace();
}
}
}
System.out.println("Instance: "+instance); //查看生成的实例;
}
/*************************************************************************/
public String user;
public String password;
public ConstructorTest(){}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "ConstructorTest [user=" + user + ", password=" + password + "]";
}
}