编程练习。
来源:2-9 自由编程
sx1011
2020-09-08 22:27:47
package com.imooc.reflect; import com.imooc.reflect.entity.Book; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /* 1)通过Constructor获得有参构造方法,并实例化Goods类的对象 2)获取当前类的所有成员变量,判断是public或者private修饰的,并进行输出。 */ public class BookTest { public static void main(String[] args) { try { Class bookClass = Class.forName("com.imooc.reflect.entity.Book"); Constructor constructor = bookClass.getConstructor(new Class[]{ Integer.class,String.class,Double.class }); Book book = (Book)constructor.newInstance(new Object[]{ 1011,"Java核心技术",50d }); Field[] fields = bookClass.getDeclaredFields(); for (Field field:fields){ if(field.getModifiers()==1){ Object val = field.get(book); System.out.println(field.getName() + ":" + val); }else if (field.getModifiers()==2){ String methodName = "get" + field.getName().substring(0,1).toUpperCase() + field.getName().substring(1); Method getMethod = bookClass.getMethod(methodName); Object ret = getMethod.invoke(book); System.out.println(field.getName() + ":" + ret); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }
package com.imooc.reflect.entity; /* 1、创建图书类Book,类的结构如下: 1)私有属性:图书编号、图书名称;公有属性:图书价格 2)无参构造及带参构造 3)get和set方法 4)toString()方法 */ public class Book { private Integer bno; private String bname; public Double bprice; public Book(){ } public Book(Integer bno,String bname,Double bprice){ this.setBname(bname); this.setBno(bno); this.setBprice(bprice); } public Integer getBno() { return bno; } public void setBno(Integer bno) { this.bno = bno; } public String getBname() { return bname; } public void setBname(String bname) { this.bname = bname; } public Double getBprice() { return bprice; } public void setBprice(Double bprice) { this.bprice = bprice; } @Override public String toString() { return "Book{" + "bno=" + bno + ", bname='" + bname + '\'' + ", bprice=" + bprice + '}'; } }
1回答
同学你好,同学的代码完成的不错哦,很棒,继续加油!!
如果我的回答解决了你的问题,请采纳,祝学习愉快.