public static void main(String[] args) {
		Student stu1 = new Student();
		stu1.setId(1);
		stu1.setName("张三");
		
//		Class c = Student.class.getClass();
		try {
			Class c = stu1.getClass();
			Field f[] = c.getDeclaredFields();
			System.out.println("字段数组大小:"+f.length);
			System.out.println("字段1:"+f[0].getName());
			System.out.println("字段2:"+f[1].getName());
			
			Method m = c.getMethod("getId", null);
			System.out.println("字段1-值:"+m.invoke(stu1,null));
			Method m2 = c.getMethod("getName", null);
			System.out.println("字段2-值:"+m2.invoke(stu1,null));
			
			//循环的方式
			for (int i = 0; i < f.length; i++) {
				String str = f[i].getName().substring(0,1).toUpperCase()+f[i].getName().substring(1);
				Method m3 = c.getMethod("get"+str, null);
				System.out.println("--字段--"+f[i].getName()+"--值--"+m3.invoke(stu1,null));
			}
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
	}

补充:Student.java  属性id,name,分别提供setter,getter方法。

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-19
  • 2022-01-22
  • 2022-12-23
猜你喜欢
  • 2021-11-07
  • 2022-12-23
  • 2021-06-25
  • 2022-02-22
  • 2022-02-24
  • 2021-07-08
  • 2021-07-20
相关资源
相似解决方案