一、反射
1.定义:Java的反射(reflection)机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任
意一个对象,都能够调用它的任意方法和属性,既然能拿到那么,我们就可以修改部分类型信息;这种动态获取信
息以及动态调用对象方法的功能称为java语言的反射(reflection)机制
2.根本:就是从Class对象出发的
3.反射相关的类:
4.获得Class对象的三种方式:
5.class类中的相关方法:
(1)常用获得类的相关方法:
(2)常用获得类中属性的相关方法:
(3)获得类中构造器的相关方法:
6.应用
//创建对象
public static void reflectNewInstance() {
try {
Class<?> c1 = Class.forName("Student");
Student student = (Student) c1.newInstance();
System.out.println(c1);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
// 反射私有的构造方法 屏蔽内容为获得公有的构造方法
public static void reflectPrivateConstructor() {
try {
Class<?> c1 = Class.forName("Student");
//传入对应的参数
Constructor<?> declaredConstructor =
c1.getDeclaredConstructor(String.class,int.class);
//设置为true后可修改访问权限
declaredConstructor.setAccessible(true);
Object objectStudent =
declaredConstructor.newInstance("zm",111);
Student student = (Student) objectStudent;
System.out.println(student);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
// 反射私有属性
public static void reflectPrivateField() {
try {
Class<?> c1 = Class.forName("Student");
Field field = c1.getDeclaredField("name");
field.setAccessible(true);
Object o = c1.newInstance();
Student student = (Student) o;
field.set(student,"小明");
String name = (String) field.get(student);
System.out.println(name);
} catch (ClassNotFoundException | NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
}
}
// 反射私有方法
public static void reflectPrivateMethod() {
try {
Class<?> c1 = Class.forName("Student");
Method method =
c1.getDeclaredMethod("function", String.class);
System.out.println("私有方法名:"+method.getName());
method.setAccessible(true);
Object o = c1.newInstance();
Student student = (Student) o;
method.invoke(student,"反射私有方法");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
reflectNewInstance();
System.out.println();
reflectPrivateConstructor();
System.out.println();
reflectPrivateField();
System.out.println();
reflectPrivateMethod();
}
二、枚举
1.java当中的枚举实际上是对象,默认继承了java.lang.Enum
RED是一个对象。
2.Enum类常用的方法:
三、Lambda表达式