class的意义
作为程序运作过程中用于标识和维护某个类运行时候的状态,可以通过反射来获取到相应的对象属性。这个Class和我们常见的class还是有所区别的,前者更多的是保存运行时的类信息,后者则只是一个关键字而已。
反射的理解
反射是一种可以获取jvm里面动态信息的加载方式。反射的优点在于可以动态化地加载类的属性和方法,是java语言中比较灵活的一种特性。但是反射也有他自己的缺点,毕竟需要提前进行编译的代码才能被反射操作,操作效率上会慢于直接操作java程序。
通过class我们最常用的就是反射技巧,可以借助反射来获取类里面我们所需要的变量,方法,构造函数等信息,同时我们还可以借助反射来进行类的实例化操作。
接下来我们闲话不多说,直接写一个demo来进行总结和归纳
import org.junit.Before;
import org.junit.Test;
import 自定义类加载器.User;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* @author idea
* @data 2019/2/12
*/
public class ReflectTest {
User user;
Class userClass;
@Before
public void setUp() {
user = new User("idea", "pwd");
userClass = user.getClass();
}
/**
* 获取包名和类名
*/
@Test
public void getClassAndPackageName() {
System.out.println(userClass.getName());
}
/**
* 获取单独的类名
*/
@Test
public void getClassName() {
System.out.println(userClass.getSimpleName());
}
/**
* 获取数组名称
*/
@Test
public void getComponentName() {
String[] arr = {"asd", "vbbb"};
System.out.println(arr.getClass().getComponentType());
}
/**
* 获取方法名称的数组
*/
@Test
public void getFieldAndMethods() {
//获取所有的方法 包括父类信息
Method[] methods = userClass.getMethods();
for (Method method : methods) {
System.out.println(method.getName());
}
//获取所有的属性 包括父类信息
Field[] fields = userClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
}
/**
* 返回全部构造器数组,无论是public/private还是protected,不包括超类的成员
*/
@Test
public void getDeclaredConstructors() {
Constructor[] constructors = userClass.getDeclaredConstructors();
for (Constructor constructor : constructors) {
System.out.println(constructor.getParameterCount());
}
}
/**
* 获取当前类的修饰符
*/
@Test
public void getModifiers() {
int status = userClass.getModifiers();
System.out.println(status);
}
/**
* 创建类实例的方式
*
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchMethodException
* @throws InvocationTargetException
*/
@Test
public void classNewInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class c1 = Class.forName("java.lang.Integer");
String str = (String) Class.forName("java.lang.String").newInstance();
Constructor c2 = Class.forName("java.lang.String").getDeclaredConstructor();
c2.setAccessible(true);
String st1 = (String) c2.newInstance();
Constructor c3 = Class.forName("java.lang.String").getDeclaredConstructor(new Class[]{String.class});
c3.setAccessible(true);
String str2 = (String) c3.newInstance("idea");
System.out.println(str2);
}
}