- package com.go2think;
- import java.beans.PropertyDescriptor;
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- public class ReflectMethod {
- /**
- * 通过反射获取getName()方法
- * @param args
- * @throws Exception
- */
- public static void main(String[] args) throws Exception {
- // TODO Auto-generated method stub
- Class clazz = Class.forName("com.go2think.Person");
- Constructor cons = clazz.getConstructor(String.class);
- Method method = clazz.getMethod("getName", null);
- Object obj = cons.newInstance("黑马程序员");
- String name = (String) method.invoke(obj, null);
- System.out.println(name);
- //第二种想法,对于这种具有命名规则的java类,你完全可以看做是一个javaBean
-
- String propertyName = "name";
- PropertyDescriptor pd =
- new PropertyDescriptor(propertyName, clazz);
- //getName对应的是读方法,是一种读取属性值的操作
- Method methodgetName=pd.getReadMethod();
- String name2=(String) methodgetName.invoke(obj, null);
- System.out.println(name2);
- }
- }
复制代码 |