怎么获得java bean中的属性名称
3个回答
展开全部
/**如第二个回答所说,你应该多看jdk API文档的.*/
import java.lang.reflect.Field;
public class TestGetField {
public static void main(String[] args) {
try{
Student student = new Student(21,"banxi1988","boy");
Class sc = student.getClass();
Field[] fieldArray = sc.getFields();
System.out.println("直接得到公开的属性");
System.out.println("属性名\t属性类型\t\t属性值");
for(int i = 0; i<fieldArray.length;i++){
Field tmpField = fieldArray[i];
System.out.print(tmpField.getName()+"\t\t");
System.out.print(tmpField.getType()+"\t\t");
System.out.println(tmpField.get(student));
}
/**通过反射构造新的对象 ,然后...
Student refStudent =(Student)sc.newInstance();
**/
}catch(Exception e){
e.printStackTrace();
}
}
}
class Student{
private int age;
public String name;
private String gender;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student(int age, String name, String gender) {
super();
this.age = age;
this.name = name;
this.gender = gender;
}
}
import java.lang.reflect.Field;
public class TestGetField {
public static void main(String[] args) {
try{
Student student = new Student(21,"banxi1988","boy");
Class sc = student.getClass();
Field[] fieldArray = sc.getFields();
System.out.println("直接得到公开的属性");
System.out.println("属性名\t属性类型\t\t属性值");
for(int i = 0; i<fieldArray.length;i++){
Field tmpField = fieldArray[i];
System.out.print(tmpField.getName()+"\t\t");
System.out.print(tmpField.getType()+"\t\t");
System.out.println(tmpField.get(student));
}
/**通过反射构造新的对象 ,然后...
Student refStudent =(Student)sc.newInstance();
**/
}catch(Exception e){
e.printStackTrace();
}
}
}
class Student{
private int age;
public String name;
private String gender;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Student(int age, String name, String gender) {
super();
this.age = age;
this.name = name;
this.gender = gender;
}
}
展开全部
使用java反射机制。用属性反射。只要穿一个java类名。可以获得java的所有属性(Field).具体代码就不贴了。建议学java多查查手册。看看api。。很有帮助的。
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
什么意思!反射
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |