java 反射机制学习(一) (二)
t i = 0; i < f.length; i++) {
Field field = f[i];
System.out.println("属性名称:"+field.getName());
System.out.println("属性类型:"+field.getType());
}
Method:类的方法
Method 提供关于类或接口上单独某个方法(以及如何访问该方法)的信息。所反映的方法可能是类方法或实例方法(包括抽象方法)。 跟Field一样通过Class的四个静态方法来获得Method对象跟数组:
第一个getMethod 返回一个 Method 对象,它反映此 Class 对象所表示的类或接口的指定公共成员方法。name 参数是一个 String,用于指定所需方法的简称。parameterTypes 参数是按声明顺序标识该方法形参类型的 Class 对象的一个数组。如果 parameterTypes 为 null,则按空数组处理。
第二个getDeclaredMethod返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的指定已声明方法。name 参数是一个 String,它指定所需方法的简称,parameterTypes 参数是 Class 对象的一个数组,它按声明顺序标识该方法的形参类型。如果在某个类中声明了带有相同参数类型的多个方法,并且其中有一个方法的返回类型比其他方法的返回类型都特殊,则返回该方法;否则将从中任选一个方法。如果名称是 "” 或 “",则引发一个 NoSuchMethodException。
[java]
Class class1 = null;
try {
//com.test.hzw.bean.test_user为类的全路径名
class1 = Class.forName("com.test.hzw.bean.test_user");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method m = null;
try {
m = class1.getDeclaredMethod("getPass"); //参数填写类中任意方法的方法名称
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("方法名称:"+m.getName());
System.out.println("方法返回类型:"+m.getReturnType());
Class class1 = null;
try {
//com.test.hzw.bean.test_user为类的全路径名
class1 = Class.forName("com.test.hzw.bean.test_user");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method m = null;
try {
m = class1.getDeclaredMethod("getPass"); //参数填写类中任意方法的方法名称
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
System.out.println("方法名称:"+m.getName());
System.out.println("方法返回类型:"+m.getReturnType());
第三个getMethods返回一个包含某些 Method 对象的数组,这些对象反映此 Class 对象所表示的类或接口(包括那些由该类或接口声明的以及从超类和超接口继承的那些的类或接口)的公共 member 方法。数组类返回从 Object 类继承的所有(公共)member 方法。返回数组中的元素没有排序,也没有任何特定的顺序。如果此 Class 对象表示没有公共成员方法的类或接口,或者表示一个基本类型或 void,则此方法返回长度为 0 的数组。
第四个getDeclaredMethods返回 Method 对象的一个数组,这些对象反映此 Class 对象表示的类或接口声明的所有方法,包括公共、保护、默认(包)访问和私有方法,但不包括继承的方法。返回数组中的元素没有排序,也没有任何特定的顺序。如果该类或接口不声明任何方法,或者此 Class 对象表示一个基本类型、一个数组类或 void,则此方法返回一个长度为 0 的数组。类初始化方法 不包含在返回数组中。如果该类声明带有相同参数类型的多个公共成员方法,则它们都包含在返回的数组中。
[java]
Class class1 = null;
try {
//com.test.hzw.bean.test_user为类的全路径名
class1 = Class.forName("com.test.hzw.bean.test_user");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method[] ms = class1.getDeclaredMethods();
for (int i = 0; i < ms.length; i++) {
Method m = ms[i];
System.out.println("方法名称:"+m.getName());
System.out.println("方法返回类型:"+m.getReturnType());
}
Class class1 = null;
try {
//com.test.hzw.bean.test_user为类的全路径名
class1 = Class.forName("com.test.hzw.bean.test_user");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Method[] ms = class1.getDeclaredMethods();
for (int i = 0; i < ms.length; i++) {
Method m = ms[i];
System.out.println("方法名称:"+m.getName());
System.out.println("方法返回类型:"+m.getReturnType());
}
Constructor:类的构造
提供关于类的单个构造方法的信息以及对它的访问权限。构造跟上面的两个类一样、通过Class的四个静态方法来获取Constructor 对象跟数组: