java 基础 反射
一、接口
二、反射
getFileds() 返回一个 Field 对象的数组,包括这个类或者超类的公有域
getFiled(name) 根据名称返回对应的域
getDeclaredFields() 返回 Field 对象数组,包括这个类的全部域
getType() 返回描述域所属类型的 Class 对象
SetAccessible(true) 屏蔽 java 语言的访问检查,使得私有属性也可以被查询和设置
get(obj) set()
6. Method、Constructor 与 Field 类似。
获取方法指针:Method m = obj.class.getMethod(方法名)
调用方法: String n = m.invoke(obj,... 参数)
注意:如果是调用静态方法,则第一参数为空
以下附录一个小例子:
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.lang.reflect.Modifier;
- import java.util.Scanner;
- import java.lang.Double;
- /**
- * Created by cnslp on 2017/4/22.
- */
- public class ReflectionTest {
- public static void printfiled(Class c){
- Field[] fields = c.getDeclaredFields();
- for (Field f : fields){
- String modifier = Modifier.toString(f.getModifiers());
- if (modifier.length()>0){
- System.out.print(modifier+" ");
- }
- Class type = f.getType();
- System.out.print(type.getName()+" ");
- System.out.print(f.getName());
- System.out.println(";");
- }
- System.out.println();
- }
- public static void printConstruct(Class c){
- Constructor[] constructors = c.getConstructors();
- for (Constructor constructor : constructors){
- String modifier = Modifier.toString(constructor.getModifiers());
- if (modifier.length()>0){
- System.out.print(" "+modifier+" ");
- }
- String name = constructor.getName();
- System.out.print(name+"(");
- Class[] paramTypes = constructor.getParameterTypes();
- int j=0;
- for (Class cc : paramTypes){
- if (j>0)
- System.out.print(",");
- System.out.print(cc.getName());
- j++;
- }
- System.out.println(");");
- }
- System.out.println("");
- }
- public static void printMethod(Class c){
- Method[] methods = c.getMethods();
- for (Method method : methods){
- String modifier = Modifier.toString(method.getModifiers());
- if (modifier.length()>0){
- System.out.print(" "+modifier+" ");
- }
- String name = method.getName();
- System.out.print(name+"(");
- Class[] paramTypes = method.getParameterTypes();
- int j=0;
- for (Class cc : paramTypes){
- if (j>0)
- System.out.print(",");
- System.out.print(cc.getName());
- j++;
- }
- System.out.println(");");
- }
- }
- public static void main(String[] args) {
- String name;
- if (args.length>0)
- name = args[0];
- else {
- Scanner in = new Scanner(System.in);
- System.out.println("please input a class name");
- name = in.nextLine();
- }
- try {
- Class c = Class.forName(name);
- Class father = c.getSuperclass();
- String modefiers = Modifier.toString(c.getModifiers());
- System.out.println(modefiers+" class "+c.getName()+" extends "+father.getName()+"{");
- printfiled(c);
- printConstruct(c);
- printMethod(c);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- }
- }
- }
来源: http://www.bubuko.com/infodetail-2035971.html