一:反射概述:
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性;这种动态获取的信息以及动态调用对象的方法的功能称为java语言的反射机制。
二:反射加载过程:
三:反射代码示例:
1.Person类
package com.qfedu.a_reflect;
public class Person {
private int id;
private String name;
public int test;
public static int testStatic = 10 ;
private Person () {}
public Person (int id, String name) {
this .id = id;
this .name = name;
}
public int getId () {
return id;
}
public void setId (int id) {
this .id = id;
}
public String getName () {
return name;
}
public void setName (String name) {
this .name = name;
}
public static void eat () {
System.out .println("黄焖鸡米饭~~~" );
}
public void sleep (int num) {
System.out .println(name + "每天睡" + num + "个小时" );
}
public void game () {
System.out .println("大吉大利,今晚吃鸡~~~" );
}
private void testPrivate () {
System.out .println("这是一个Private修饰的私有化方法" );
}
@Override
public String toString () {
return "Person [id=" + id + ", name=" + name + "]" ;
}
}
2.反射代码获取Person类的属性和方法等
package com .qfedu .a _reflect
import java.lang .reflect .Constructor
import java.lang .reflect .InvocationTargetException
public class GetClassConstructor {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException,
SecurityException,InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
//获取Class对象 方法一:
Class c1 = Class.forName ("com.qfedu.a_reflect.Person" )
//获取Class对象 方法二:
Class c= Person.class
//获取公共构造方法
Constructor[] publicConstructor = c.getConstructors ()
for (Constructor constructor : publicConstructor) {
System.out .println ("公共构造方法: " + constructor)
}
System.out .println ("\n-----------------------------------" )
//获取所有构造方法
Constructor[] allConstructor = c.getDeclaredConstructors ()
for (Constructor constructor : allConstructor) {
System.out .println ("所有构造方法: " + constructor)
}
System.out .println ("\n-----------------------------------" )
//获取一个公共的构造方法
Constructor aPublicConstruct = c.getConstructor (int.class , String.class )
System.out .println ("获取一个公共的构造方法: " + aPublicConstruct)
//获取一个私有的构造方法
Constructor aPrivateConstrctor = c.getDeclaredConstructor (null)
System.out .println ("获取一个私有的构造方法 : " + aPrivateConstrctor)
System.out .println ("\n-----------------------------------" )
Person p = (Person) c.getConstructor (int.class , String.class ).newInstance (1 , "傻子" )
System.out .println ("ID: " + p.getId () + ", Name: " + p.getName ())
p.sleep (5 )
p.eat ()
p.testStatic = 5
System.out .println (p.testStatic )
System.out .println ("\n-----------------------------------" )
Constructor aPrivateConstructor2 = c.getDeclaredConstructor (null)
aPrivateConstructor2.setAccessible (true)
Person p2 = (Person)aPrivateConstructor2.newInstance (null)
p2.test = 4
System.out .println (p2.test )
}
}
文章还未总结完,以后再补。