本章主要介绍反射、枚举以及lambda表达式的功能以及如何使用。
Java的反射(reflection)机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性,既然能拿到那么,我们就可以修改部分类型信息;这种动态获取信息以及动态调用对象方法的功能称为java语言的反射(reflection)机制。
1. 在日常的第三方应用开发过程中,经常会遇到某个类的某个成员变量、方法或是属性是私有的或是只对系统应用开放,这时候就可以利用Java的反射机制通过反射来获取所需的私有成员或是方法 。 2. 反射最重要的用途就是开发各种通用框架,比如在spring中,我们将所有的类Bean交给spring容器管理,无论是XML配置Bean还是注解配置,当我们从容器中获取Bean来依赖注入时,容器会读取配置,而配置中给的就是类的信息,spring根据这些信息,需要创建那些Bean,spring就动态的创建这些类
Java程序中许多对象在运行时会出现两种类型:运行时类型(RTTI)和编译时类型,例如Person p = new Student();这句代码中p在编译时类型为Person,运行时类型为Student。程序需要在运行时发现对象和类的真实信息。而通过使用反射程序就能判断出该对象和类属于哪些类。
在讲解这些类之前,我们需要先构建一个类,方便进行反射的操作:
class Student{
//私有属性name
private String name = "hulalala";//公有属性age
public int age = 20;
//不带参数的构造方法
public Student(){
System.out.println("Student()");
}
private Student(String name,int age) {
this.name = name;
this.age = age;
System.out.println("Student(String,name)");
}
private void eat(){
System.out.println("i am eat");
}
public void sleep(){
System.out.println("i am sleep");
}
private void function(String str) {
System.out.println(str);
} @
Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
在反射之前,我们需要做的第一步就是先拿到当前需要反射的类的Class对象,然后通过Class对象的核心方法,达到反射的目的,即:在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性,既然能拿到那么,我们就可以修改部分类型信息。
(1)使用 Class.forName("类的全路径名"); 静态方法。前提:已明确类的全路径名。
/*通过 Class 对象的 forName() 静态方法来获取,用的最多,
但可能抛出 ClassNotFoundException 异常
*/
Class c3 = null;
try {
//注意这里是类的全路径,如果有包需要加包的路径4.2.2 反射的使用接下来我们开始使用反射,我们依旧反射上面的Student类,把反射的逻辑写到另外的类当中进行理解 注意:所有和反射相关的包都在 import java.lang.reflect 包下面。
c3 = Class.forName("Student");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
(2)使用 .class 方法。 说明:仅适合在编译前就已经明确要操作的 Class
/* 直接通过 类名.class 的方式得到,该方法最为安全可靠,程序性能更高
这说明任何一个类都有一个隐含的静态成员变量 class
*/
Class c2 = Student.class;
(3)使用类对象的 getClass() 方法
1.通过getClass获取Class对象
*/
Student s1 = new Student();
Class c1 = s1.getClass();
/*
创建对象:
/**
* 创建对象
*/
private static void reflectNewInstance() {
try {
Class<?> classStudent = Class.forName("Student");
Object newInstance = classStudent.newInstance();
Student student = (Student) newInstance;
System.out.println("获得学生对象:"+student);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* 反射私有构造方法
*/
private static void reflectPrivateConstructor() {
try {
Class<?> classStudent = Class.forName("Student");
Constructor<?> declaredConstructor =
classStudent.getDeclaredConstructor(String.class, int.class);
declaredConstructor.setAccessible(true);
Object zhangsan = declaredConstructor.newInstance("zhangsan", 17);
Student student = (Student) zhangsan;
System.out.println("获得私有构造哈数且修改姓名和年龄"+student);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
/**
* 反射私有属性
*/
private static void reflectPrivateField() {
try {
Class<?> classStudent = Class.forName("Student");
Field field = classStudent.getDeclaredField("name");
field.setAccessible(true);
Object newInstance = classStudent.newInstance();
Student student = (Student) newInstance;
field.set(student,"李四");
String name = (String) field.get(student);
System.out.println("反射私有属性修改了name:"+ name);
} catch (Exception e) {
e.printStackTrace();
}
}
private static void reflectPrivateMethod() throws Exception {
Class<?> classStudent = Class.forName("Student");
Method methodStudent = classStudent.getDeclaredMethod("function",String.class);
System.out.println("私有方法的方法名为:"+methodStudent.getName());
methodStudent.setAccessible(true);
Object objectStudent = classStudent.newInstance();
Student student = (Student) objectStudent;
methodStudent.invoke(student,"我是给私有的function函数传的参数");
}
优点: 1. 对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法 2. 增加程序的灵活性和扩展性,降低耦合性,提高自适应能力 3. 反射已经运用在了很多流行框架如:Struts、Hibernate、Spring 等等。 缺点: 1. 使用反射会有效率问题。会导致程序效率降低。 2. 反射技术绕过了源代码的技术,因而会带来维护问题。反射代码比相应的直接代码更复杂
枚举是在JDK1.5以后引入的。主要用途是:将一组常量组织起来,在这之前表示一组常量通常使用定义常量的方式:
public static final int RED = 1;
public static final int GREEN = 2;
public static final int BLACK = 3;
但是常量举例有不好的地方,例如:可能碰巧有个数字1,但是他有可能误会为是RED,现在我们可以直接用枚举来进行组织,这样一来,就拥有了类型,枚举类型。而不是普通的整形1
public enum TestEnum {
RED,BLACK,GREEN;
}
优点:将常量组织起来统一进行管理 场景:错误状态码,消息类型,颜色的划分,状态机等等.... 本质:是 java.lang.Enum 的子类,也就是说,自己写的枚举类,就算没有显示的继承 Enum ,但是其默认继承了这个类。
1、switch语句
public enum TestDemo {
RED,
GREEN,
BLACK;
public static void main(String[] args) {
TestDemo testDemo = TestDemo.RED;
switch (testDemo) {
case RED -> System.out.println("RED");
case GREEN -> System.out.println("GREEN");
case BLACK -> System.out.println("BLACK");
}
}
}
2.常用方法
public static void main(String[] args) {
TestDemo[] testDemos = TestDemo.values();
for (int i = 0; i < testDemos.length; i++) {
System.out.println(testDemos[i] + " " + testDemos[i].ordinal());
}
System.out.println("===============");
TestDemo testDemo = TestDemo.valueOf("RED");
System.out.println("testDemo="+testDemo);
System.out.println("===============");
System.out.println(RED.compareTo(GREEN));
}
public enum TestDemo {
RED("红色",1),
GREEN("绿色",2),
BLACK("黑色",3);
public String name;
public int val;
TestDemo(String name,int val) {
this.name = name;
this.val = val;
}
public static void main(String[] args) {
TestDemo[] testDemos = TestDemo.values();
for (int i = 0; i < testDemos.length; i++) {
System.out.println(testDemos[i].name+" "+testDemos[i].val );
}
}
}
优点: 1. 枚举常量更简单安全 。 2. 枚举具有内置方法 ,代码更优雅 3.枚举可以避免反射和序列化问题 缺点: 1. 不可继承,无法扩展
不能通过反射来创建枚举对象
语法:
基本语法: (parameters) -> expression 或 (parameters) ->{ statements; } Lambda表达式由三部分组成: 1. paramaters:类似方法中的形参列表,这里的参数是函数式接口里的参数。这里的参数类型可以明确的声明 也可不声明而由JVM隐含的推断。另外当只有一个推断类型时可以省略掉圆括号。 2. ->:可理解为“被用于”的意思 3. 方法体:可以是表达式也可以代码块,是函数式接口里方法的实现。代码块可返回一个值或者什么都不反 回,这里的代码块块等同于方法的方法体。如果是表达式,也可以返回一个值或者什么都不反回
// 1. 不需要参数,返回值为 2
() -> 2
// 2. 接收一个参数(数字类型),返回其2倍的值
x -> 2 * x
// 3. 接受2个参数(数字),并返回他们的和
(x, y) -> x + y
// 4. 接收2个int型整数,返回他们的乘积
(int x, int y) -> x * y
// 5. 接受一个 string 对象,并在控制台打印,不返回任何值(看起来像是返回void)
(String s) -> System.out.print(s)
函数式接口:
要了解Lambda表达式,首先需要了解什么是函数式接口,函数式接口定义:一个接口有且只有一个抽象方法 。 注意: 1. 如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口 2. 如果我们在某个接口上声明了 @FunctionalInterface 注解,那么编译器就会按照函数式接口的定义来要求该接口,这样如果有两个抽象方法,程序编译就会报错的。所以,从某种意义上来说,只要你保证你的接口中只有一个抽象方法,你可以不加这个注解。加上就会自动进行检测的。
定义方式:
@FunctionalInterface
interface NoParameterNoReturn {
//注意:只能有一个方法
void test();
}
但是这种方式也是可以的:
@FunctionalInterface
interface NoParameterNoReturn {
void test();
default void test2() {
System.out.println("JDK1.8新特性,default默认方法可以有具体的实现");
}
}
先引入好接口方便后续使用
//无返回值无参数
@FunctionalInterface
interface NoParameterNoReturn {
void test();
}
//无返回值一个参数
@FunctionalInterface
interface OneParameterNoReturn {
void test(int a);
}
//无返回值多个参数
@FunctionalInterface
interface MoreParameterNoReturn {
void test(int a,int b);
}
//有返回值无参数
@FunctionalInterface
interface NoParameterReturn {
int test();
}
//有返回值一个参数
@FunctionalInterface
interface OneParameterReturn {
int test(int a);
}
//有返回值多参数
@FunctionalInterface
interface MoreParameterReturn {
int test(int a,int b);
}
public static void main(String[] args) {
//有返回值多参数
MoreParameterReturn moreParameterReturn = (a,b)->{
return a*b;
};
System.out.println(moreParameterReturn.test(10, 20));
System.out.println("============");
//无返回值多个参数
MoreParameterNoReturn moreParameterNoReturn = (a,b) ->{
System.out.println(a+b);
};
moreParameterNoReturn.test(10,20);
}
创建小跟堆
public static void main(String[] args) {
//常规方法
PriorityQueue<Integer> priorityQueue = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
});
//lambda
PriorityQueue<Integer> priorityQueue1 = new PriorityQueue<>((o1, o2) -> o1-o2);
}
语法精简: 1. 参数类型可以省略,如果需要省略,每个参数的类型都要省略。 2. 参数的小括号里面只有一个参数,那么小括号可以省略 3. 如果方法体当中只有一句代码,那么大括号可以省略 4. 如果方法体中只有一条语句,且是return语句,那么大括号可以省略,且去掉return关键字
匿名内部类就是没有名字的内部类 。我们这里只是为了说明变量捕获,所以,匿名内部类只要会使用就好,那么下面我们来,简单的看看匿名内部类的使用就好了
@FunctionalInterface
interface MoreParameterReturn {
int test(int a,int b);
}
public static void main(String[] args) {
MoreParameterReturn moreParameterReturn = new MoreParameterReturn() {
@Override
public int test(int a,int b) {
return a-b;
}
};
System.out.println(moreParameterReturn.test(30, 20));
}
(1)匿名内部类的变量捕获:
public static void main(String[] args) {
int c = 100;
MoreParameterReturn moreParameterReturn = new MoreParameterReturn() {
@Override
public int test(int a,int b) {
System.out.println("c="+c);
return a-b;
}
};
System.out.println(moreParameterReturn.test(30, 20));
}
但是不可以修改值 ,在Lambda里面也是同理,可以获取,不能修改;
List接口:
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
list.add("lambda");
list.add("hi");
list.add("lambda");
//常规写法
list.forEach(new Consumer<String>(){
@Override
public void accept(String str){
//简单遍历集合中的元素。
System.out.println(str+" ");
}
});
System.out.println("============");
//lambda
list.forEach(s -> {
System.out.println(s);
});
}
Map接口:
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "hello");
map.put(2, "lambda");
map.put(3, "hi");
map.put(4, "lambda");
map.forEach(new BiConsumer<Integer, String>(){
@Override
public void accept(Integer k, String v){
System.out.println(k + "=" + v);
}
});
System.out.println("=============");
map.forEach((k,v)-> System.out.println(k + "=" + v));
}
Lambda表达式的优点很明显,在代码层次上来说,使代码变得非常的简洁。缺点也很明显,代码不易读。
优点: 1. 代码简洁,开发迅速 2. 方便函数式编程 3. 非常容易进行并行计算 4. Java 引入 Lambda,改善了集合操作 缺点: 1. 代码可读性变差 2. 在非并行计算中,很多计算未必有传统的 for 性能要高 3. 不容易进行调试
后期博主会陆续更新Java 的知识
如有不足之处欢迎补充交流
看到这里的友友们,支持一下博主,来个免费三连,感谢! ! !