前些天做的题目,做得不完美,求高手指教:
题目: 存在一个JavaBean,它包含以下几种可能的属性:
* 1:boolean/Boolean 2:int/Integer 3:String 4:double/Double
* 属性名未知,现在要给这些属性设置默认值,以下是要求的默认值: String类型的默认值为字符串 www.itheima.com
* int/Integer类型的默认值为100 boolean/Boolean类型的默认值为true double/Double的默认值为0.01D.
* 只需要设置带有getXxx/isXxx/setXxx方法的属性,非JavaBean属性不设置,请用代码实现- public class Demo {
- public static void main(String[] args) throws Exception {
- JavaBean jb = new JavaBean();
-
-
- // 设置值
- setProperties(jb, "bool", true);
- setProperties(jb, "inte", 100);
- setProperties(jb, "string", "www.itheima.com");
- setProperties(jb, "doub", 0.01D);
- // 获取值
- System.out.println(getProperty(jb, "bool"));
- System.out.println(getProperty(jb, "inte"));
- System.out.println(getProperty(jb, "string"));
- System.out.println(getProperty(jb, "doub"));
- }
- // 定义获取属性 的方法
- private static Object getProperty(JavaBean jb, String propertyName)
- throws IntrospectionException, IllegalAccessException,
- InvocationTargetException {
- PropertyDescriptor pb = new PropertyDescriptor(propertyName, jb
- .getClass());
- Method methodGetX = pb.getReadMethod();
-
- Object retVal = methodGetX.invoke(jb);
- return retVal;
- }
- // 定义设置属性的方法
- private static void setProperties(JavaBean jb, String propertyName,
- Object value) throws IntrospectionException,
- IllegalAccessException, InvocationTargetException {
- PropertyDescriptor pb = new PropertyDescriptor(propertyName, jb
- .getClass());
- Method methodSetX = pb.getWriteMethod();
- methodSetX.invoke(jb, value);
- }
- }
- // 编写JavaBean类
- class JavaBean {
- // 定义成员变量
- private Boolean bool;
- private Integer inte;
- private String string;
- private Double doub;
- // 编写set和get方法
- public Boolean getBool() {
- return bool;
- }
- public void setBool(Boolean bool) {
- this.bool = bool;
- }
- public Integer getInte() {
- return inte;
- }
- public void setInte(Integer inte) {
- this.inte = inte;
- }
- public String getString() {
- return string;
- }
- public void setString(String string) {
- this.string = string;
- }
- public Double getDoub() {
- return doub;
- }
- public void setDoub(Double doub) {
- this.doub = doub;
- }
- }
复制代码 |