欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

javaBean

程序员文章站 2022-05-24 08:47:45
...
[quote]

package com.java.day01;

import java.lang.reflect.Method;

public class BeanUtil {

//javaBean
//1,公共无参构造方法;
//2,属性存取方法符合set-get 规范;

public static void setProperty (
Object o,String name,Object value) throws Exception{//属性变为set方法;
String methodName =
"set" + name.substring(0,1).toUpperCase()+
name.substring(1);
Method m = null;
Class paramClass = value.getClass();
if(paramClass == Integer.class){
//setAge(Integer),getAge(int)
try {
m = o.getClass().getMethod(methodName, new Class[]{value.getClass()});
} catch (Exception e) {
m = o.getClass().getMethod(methodName, new Class[]{int.class});
}
}else{
m = o.getClass().getMethod(methodName, new Class[]{int.class});
}
m.invoke(o, new Object[]{value});
}

public static Object getProperty(Object o,String name) throws Exception{
String methodName =
"get" + name.substring(0,1).toUpperCase()+
name.substring(1);
Method m = o.getClass().getMethod(methodName, null);
return m.invoke(o, null);
}
public static void main(String[] args) throws Exception{
Student stu = new Student();
setProperty(stu, "age", 23);
System.out.println(stu.getAge());
}
}
class Student{
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}


}

[/quote]