java 反射

java 反射

JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。

获取所有构造函数

/**
	 * Prints all constructors of a class
	 * 
	 * @param cl
	 *            a class
	 */
	public static void printConstructors(Class cl) {
		System.out.println("printConstructors");
		Constructor[] constructors = cl.getDeclaredConstructors();

		for (Constructor c : constructors) {
			String name = c.getName();
			System.out.print("   " + Modifier.toString(c.getModifiers()));
			System.out.print(" " + name + "(");

			// print parameter types
			Class[] paramTypes = c.getParameterTypes();
			for (int j = 0; j < paramTypes.length; j++) {
				if (j > 0)
					System.out.print(", ");
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}
	}

获取所有方法

/**
	 * Prints all methods of a class
	 * 
	 * @param cl
	 *            a class
	 */
	public static void printMethods(Class cl) {
		System.out.println("printMethods");
		Method[] methods = cl.getDeclaredMethods();

		for (Method m : methods) {
			Class retType = m.getReturnType();
			String name = m.getName();

			// print modifiers, return type and method name
			System.out.print("   " + Modifier.toString(m.getModifiers()));
			System.out.print(" " + retType.getName() + " " + name + "(");

			// print parameter types
			Class[] paramTypes = m.getParameterTypes();
			for (int j = 0; j < paramTypes.length; j++) {
				if (j > 0)
					System.out.print(", ");
				System.out.print(paramTypes[j].getName());
			}
			System.out.println(");");
		}
	}

获取所有字段

/**
	 * Prints all fields of a class
	 * 
	 * @param cl
	 *            a class
	 */
	public static void printFields(Class cl) {
		System.out.println("printFields");
		Field[] fields = cl.getDeclaredFields();

		for (Field f : fields) {
			Class type = f.getType();
			String name = f.getName();
			System.out.print("   " + Modifier.toString(f.getModifiers()));
			System.out.println(" " + type.getName() + " " + name + ";");
		}
	}

调用无参方法

                Class c4 = Class.forName("reflection.Test.Person");//获取类
		Constructor co = c4.getConstructor(null);//获取构造函数
		Object obj = co.newInstance(null);//使用构造函数实例化一个对象
		Method m = c4.getMethod("show", null);//获取一个方法
		m.invoke(obj, null);//通过对象调用方法

class.forname

class.forName,要求JVM查找并加载指定的类,也就是说JVM会执行该类的静态代码段,返回一个类,以后就不会再装载了

.newInstance() 后才创建一个对象

Class的最大作用就是实现了动态加载类,为多态提供了很好的帮助

newInstance与new的区别

new一个类,这个类可以没有被加载,可以调用任何构造函数

newInstance一个类,这个类必须已经被加载了,只能调用无参构造函数

class A
{
    void aa()
    {
        System.out.println ("A里的");    
        
    }    
    
}
class B extends A
{
    void aa()
    {
        System.out.println ("B里的");    
        
    }    
    
}
class C extends A
{
    void aa()
    {
        System.out.println ("C里的");    
        
    }    
    
}


public class ClassDemo
{
    
    public static void main(String[] args)
    {
        ClassDemo t=new ClassDemo();
        t.show("C");
    }
    void show(String name)
    {
        try
        {
             A show=(A)Class.forName(name).newInstance();
        show.aa();
    }
    catch(Exception e)
    {
        System.out.println (e);
        }
    }
}


调用有参方法

            //调用有参数构造函数
	    Method showdetail = c4.getMethod("showdetail", new Class[] {int.class,String.class});
            //获得参数Object
	    Object[] arguments = new Object[]{new Integer(23),new String("abc")};
	    showdetail.invoke(obj, arguments);




你可能感兴趣的:(java,反射)