反射把字符串转换为对应的实体对象
- 有一新闻服务器,会以字符串的形式返回新闻信息和作者信息,字符串格式如下:
- 字符串都是规范的键值对形式:“key1:value1,key2:value2,key3:value3,key4:value4”
- 其中key是字符串,value可以是字符串也可以是整数
- 例如:“id:100001,title:美联储加息,content:据路透社透露,美国有望在下一个月调整利率,author:张三”
编写代码完成将对应的字符串转化为对应的实体对象
创建一个类
public class News {
private String id;
private String title;
private String content;
private String author;
public News() {
}
public News(String id, String title, String content, String author) {
this.id = id;
this.title = title;
this.content = content;
this.author = author;
}
@Override
public String toString() {
return "News{" +
"id='" + id + '\'' +
", title='" + title + '\'' +
", content='" + content + '\'' +
", author='" + author + '\'' +
'}';
}
主类
```public class Test {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
String s="id:100001,title:美联储加息,content:据路透社透露,美国有望在下一个月调整利率,author:张三";
Class<News> n = News.class;
Constructor<News> con = n.getConstructor( );
News news = con.newInstance();
String[] split = s.split(",");
for (String str:split){
String[] strings = str.split(":");
Field field = n.getDeclaredField(strings[0]);
field.setAccessible(true);
field.set(news,strings[1]);
}
System.out.println(news);
}
}