反射2:获取类的方法(通过方法名调用方法),属性,声明
2015-10-02 20:11
519 查看
package cn.itcast.jdbc; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import cn.itcast.domain.User; public class ReflectTest { public static void main(String[] args) throws Exception { Class clazz = User.class; Object obj = create(clazz); System.out.println(obj); System.out.println("---------"); invoke1(obj, "showName"); System.out.println("---------"); field(clazz); } // 给定一个类,构造出一个对象。 static Object create(Class clazz) throws Exception { Constructor con = clazz.getConstructor(String.class); // 找到构造器 Object obj = con.newInstance("test name"); // 构造出对象 return obj; } // 通过方法名调用方法 static void invoke1(Object obj, String methodName) throws Exception { Method[] ms = obj.getClass().getMethods(); // 获得实例的方法,包括公有的和私有的,但是没有继承的方法, // ms=obj.getClass().getDeclaredMethods(); //获取实例的公有方法,包括继承的方法,但是没有私有的方法 for (Method m : ms) { // System.out.println(m.getName()); if (methodName.equals(m.getName())) m.invoke(obj, null); // 执行, } Method m = obj.getClass().getMethod(methodName, null); m.invoke(obj, null); } // 获取类的属性 static void field(Class clazz) throws Exception { Field[] fs = clazz.getDeclaredFields(); // 公有的和私有的属性 // fs = clazz.getFields(); //返回公有的属性 for (Field f : fs) System.out.println(f.getName()); } // 获取声明 static void annon(Class clazz) throws Exception { Annotation[] as = clazz.getAnnotations(); } }
User.java
package cn.itcast.domain; import java.util.Date; public class User { private int id; private String name; private Date birthday; private float money; public User() { } public User(String name) { this.name = name; } public User(float money) { this.money = money; } public void showName(){ System.out.println(this.name); } @Override public String toString() { return "id=" + this.id + " name=" + this.name + " birthday=" + this.birthday + " money=" + this.money; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public float getMoney() { return money; } public void setMoney(float money) { this.money = money; } }
相关文章推荐
- QT5 学习之路08---事件的接受与忽略
- <斜率优化><单调队列>——1.【APIO2010】特别行动队
- IntelliJ IDEA 与 Gradle + Spring项目的初次尝试
- 类和对象浅谈(2)
- LeetCode题解:Binary Tree Zigzag Level Order Traversal
- tr
- Android代码连接Wifi时被系统切换到其他Wifi的问题
- 设计模式真的能改善软件质量吗?(二)
- hdu1056 HangOver
- 无线可视门铃(2009年完成)
- sed
- Ubuntu 14.04 gconftool2与gconf-editor
- awk
- 各种排序算法集合
- uvaoj 11796 - Dog Distance
- LeetCode题解:Validate Binary Search Tree
- UESTC 1307 WINDY数 (数位DP,基础)
- 靠谱的iOS面试题(下)
- C#学习之路,学习笔记 2.3 ASCLL编码和Unicode编码
- 玩转Metasploit系列(第一集)