文章会有【原创】或者【转载】标示,部分来自Google Baidu的学习结果 {Java/PHP/Python/Ruby/Go}

Java 在学习二十八【原创】  


Java的反射

1Class类的使用;

2:方法的反射;

3:成员变量的反射;

4:数组的反射;

5:构造函数的反射;


java.lang.Class

名称(class Type 类类型)

class A {}A类本身也是java.lang.Class 对象

A a1 = new A(); A类的对象表示

package coreJava;


import java.lang.reflect.Method;


public class Test2 {


public static void main(String[] args) {

// TODO Auto-generated method stub

A a1 = new A();

//表示A类的类类型

Class c1 = A.class;

Class c2 = a1.getClass();

System.out.println(c1 == c2);

try {

System.out.println(Class.forName("coreJava.Test2"));

} catch (ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("#####################");

try {

//会调用无参数的方法来产生对象,需要做强制类型转换

A aa = (A) c1.newInstance();

aa.print();

} catch (InstantiationException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (IllegalAccessException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

System.out.println("#####################");

//动态加载类,而非编译时刻

try {

Class<?> anan = Class.forName("coreJava.A");

Object test = (A) anan.newInstance();

Method[] mtds = anan.getMethods();

for (Method md : mtds) {

System.out.println(md);

}

System.out.println("#####################");

Method method = anan.getMethod("getS",String.class);

System.out.println("带参数的" + method.invoke(test, "hello anan"));

//不带参数的

Method method2 = anan.getMethod("print");

method2.invoke(test);

Method method3 = anan.getMethod("test");

method3.invoke(test);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


class A {

public void print() {

System.out.println("hello...");

}

public String getS(String s) {

return s;

}

public static void test() {

System.out.println("hello static...");

}

}