java反射机制setter方法使用

import java.lang.reflect.Method;
public class MianTset {
// 主方法测试
public static void main(String[] args) {
try {
aaa("Student");
} catch (Exception e) {
}
}

public static void aaa(String duixiang) throws Exception {
Class myClass = Class.forName("com." + duixiang);
Object obj = myClass.newInstance();
String maxCharColName = getUpperName("name");
String methodName = "set" + maxCharColName; // set方法
Method method = myClass.getDeclaredMethod(methodName, String.class);
method.invoke(obj, "张三");
System.out.print(obj.toString());
}

public static String getUpperName(String name) {
// 拆分字段,并且组装成驼峰法命名规则
if (name.contains("_")) {
String[] spName = name.toLowerCase().split("_");
name = "";
for (String na : spName) {
name += na.substring(0, 1).toUpperCase()
+ na.substring(1).toLowerCase();
}
name = name.substring(0, 1).toUpperCase() + name.substring(1);
} else {
name = name.substring(0, 1).toUpperCase() + name.substring(1);
}
return name;
}

}


package com;


public class Student {
private String name;


public String getName() {
return name;
}


public void setName(String name) {
this.name = name;
}




@Override
public String toString() {
return "Student [name=" + name + "]";
}
}




阅读更多
上一篇写开发文档时如何生成目录结构
下一篇java前端框架总结
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭