java中的接口是类吗
224
2023-05-30
java基于反射得到对象属性值的方法
本文实例讲述了java基于反射得到对象属性值的方法。分享给大家供大家参考,具体如下:
通过反射机制得到对象中的属性和属性值 在对象中private没问题,在别的类中有时会报异常。下面的例子是在本对象中
/**
* Engine entity. @author MyEclipse Persistence Tools
*/
public class Engine implements java.io.Serializable {
// Fields
private Long engineId;
private String engineName;
private String engineType;
// Constructors
/** default constructor */
public Engine() {
}
/** minimal constructor */
public Engine(Long engineId) {
this.engineId = engineId;
}
public Engine(String engineName, String engineType) {
this.engineName = engineName;
this.engineType = engineType;
}
/** full constructor */
public Engine(Long engineId, String engineName, String engineType) {
this.engineId = engineId;
this.engineName = engineName;
this.engineType = engineType;
}
// Property accessors
public Long getEngineId() {
return this.engineId;
}
public void setEngineId(Long engineId) {
this.engineId = engineId;
}
public String getEngineName() {
return this.engineName;
}
public void setEngineName(String engineName) {
this.engineName = engineName;
}
public String getEngineType() {
return this.engineType;
}
public void setEngineType(String engineType) {
this.engineType = engineType;
}
public static void main(String[] args) throws Exception {
Engine m = new Engine("汽车","发动机");
Class clazz = m.getClass();
Field[] f = clazz.getDeclaredFields();
String[] name = field2Name(f);
Object[] value = field2Value(f, m);
showNameAndValue(name, value);
}
public static void showNameAndValue(String[] name, Object[] value) {
for (int i = 0; i < name.length; i++) {
System.out.println("--" + i + "--");
System.out.println("name:" + name[i]);
System.out.println("Value:" + value[i]);
System.out.println("-- --");
}
}
public static String[] field2Name(Field[] f) {
String[] name = new String[f.length];
for (int i = 0; i < f.length; i++) {
name[i] = f[i].getName();
}
return name;
}
public static Object[] field2Value(Field[] f, Object o) throws Exception {
Object[] value = new Object[f.length];
for (NNKhGlint i = 0; i < f.length; i++) {
value[i] = f[i].get(o);
}
return value;
}
}
如果想调用private的属性的属性值,则要调用他的get方法了具体做法是:
把field2Value方法改为如下方式,这样在别的类中也可以得到private的属性值了
public static Object[] field2Value(Field[] fields, Object o) throws Exception {
Object[] values = new Object[fields.length];
Class classType = o.getClass();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
String firstLetter = fieldName.substring(0, 1).toUpperCase();
String getMethodName = "get" + firstLetter + fieldName.substring(1);
Method getMethod = classType.getMethod(getMethodName, new Class[] {});
values[i] = getMethod.invoke(o, new Object[] {});
}
return values;
}
更多java相关内容感兴趣的读者可查看本站专题:《java日期与时间操作技巧汇总》、《Java图片操作技巧汇总》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》及《Java数据结构与算法教程》。
希望本文所述对大家java程序设计有所帮助。
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~