Java反射
1、可以通过对象反射出类的名称
getClass()
通过该机制可以完整的得到类中得完整结构,属性和方法定义
getFields() /getMethod() / getIterfaces() / getName() / getPackage()
/newInstance()/getComponentType() /isArray()/getPackage()
/getSuperClass()
获取:
Class<?>c1 = null;
c1 = Class.forName(“org.lxh.demo15.getclassdemo.X”);
/ c1 = new X().getClass()
/ c1 = X.class;
2、使用 常用
class 是反射的源头,
per = Class.forName();
per = (Person) c .newInstance();
使用以上方法进行实例化时,必须在操作类中存在无参数构造,否则无法实例化
Constructor
getModifiers() / getName() / getParameterTypes() /
存在无参构造时
Class<?> c = null;
c =Class.forName(“packageName.class”);
Person per = null;
Per = (Person) c.newInstance();
不存在无参构造时 通过constructor进行
Class<?> c = null;
c = Class.forName(“packageName.className”);
Person per = null;
Constructor<?> cons[] = null;
cons = c.getConstructors();
per =(Person)cons[0].newInstances();//调用有参构造实例化
3、取得一个类的完整结构
接口 父类 构造 方法 属性
Class Constructor Method Field 都为AccessibleObject的子类
PublicClass<?>[] getInterfaces() 取得全部接口
Public Class<?>[]getSuperClass()
getDeclaredMethods()/getMethods
getReturnType() /getParameterTypes()/getModifers()
4、获得指定方法
在使用getMethod()时要添加入参数
Method met =c1.getMethod(“MethodName”);
Met.invoke(c1.newInstance())