反射、枚举以及lambda表达式

反射

反射机制指的是j在运行过程中,对于任意一个类,都能知道这个类的所有属性和方法

反射的用途

1.在日常的第三方应用开发的过程中,经常会遇到某个类的某个成员变量、方法或者属性是私有的或者只对系统应用开放,这时候就可以利用java的反射机制通过反射来获取所需的私有成员或者是方法
2.反射最重要的用途就是开发各种通用框架

反射相关的类(重要)

在这里插入图片描述

Class类

在这里插入图片描述
从上图我们可以看到,.java文件通过编译变成.class文件,而.class文件被JVM解析为一个对象,这个对象就是java.lang.Class;Java的反射机制就是通过这个对象去获得甚至去添加这个类的属性和变化,使得这个类成为一个动态的类

Class类中的相关方法

常用获得类相关的方法

getClassLoader()      获得类的加载器
getDeclaredClasses()  返回一个数组,数组中包含该类中所有类和接口类的对象(包括私有的)
forName(String className)   根据类名返回类的对象
newInstance()   创建类的实例
getName()   获得类的完整路径名字

(重要)常用获得类中属性相关的方法(以下方法返回值为Field相关)

getField(String name)    获得某个公有的属性对象
getFields()     获得所有公有的属性对象
getDeclaredField(String name)    获得某个属性对象
getDeclaredFields()    获得所有属性对象

(重要)获得类中构造器相关的方法(以下方法返回值为Constructor相关)

getConstructor(Class...<?> parameterTypes)   获得该类中与参数类型匹配的公有构造方法
getConstructors()    获得该类的所有公有构造方法
getDeclaredConstructor(Class...<?> parameterTypes)      获得该类中与参数类型匹配的构造方法
getDeclaredConstructors()    获得该类所有构造方法

(重要)获得类中方法相关的方法(以下方法返回值为Method相关)

getMethod(String name, Class...<?> parameterTypes) 获得该类某个公有的方法
getMethods()   获得该类所有公有的方法
getDeclaredMethod(String name, Class...<?> parameterTypes)    获得该类某个方法
getDeclaredMethods()    获得该类所有方法

反射实例

要实现反射,我们第一步是要获取Class对象
获取Class对象的三个方式
1.使用Class.forName("类的全路径名“);静态方法
前提:已明确类的全路径名
2.使用.class方法
前提:仅适合在编译前就已经明确要操作的Class
3.使用类对象的getClass()方法
代码展示:

public class Test {
//因为Class只有一个对象,所以不管你实例化多少个对象,以下三个equals比较均输出为ttue
public static void main(String[] args){Class<?> c1;
try {
c1=Class.forName(className:"reflectdemo.student");
}catch(classNotFoundException e){
throw new RuntimeException(e);
}
Class<?> c2;
c2 = Student.class;

Student student= new student();
Class<?>c3 =student.getClass();
System.out.println(c1.equals(c2));
System.out.println(c1.equals(c3));
System.out.println(c3.equals(c2));


//反射私有的构造方法 屏蔽内容为获得公有的构造方法
public static void reflectPrivateConstructor(){
Class<?> c1;
try {
c1 = Class.forName(className:"reflectdemo.Student");
Constructor<Student>con=(Constructor)c1.getDeclaredconstructor(String.class,int.class);
con.setAccessible(true);//确保获取私有属性的安全性
Student student =con.newInstance("zhangsan",18);
System.out.println(student);
}catch(ClassNotFoundException e){
throw new RuntimeException(e);
}catch(NoSuchMethodExceptioncatch 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);
}
}

public class ReflectDemo {
//如何通过反射 实例化对象
public static void reflectNewInstance(){
Class<?> c1;
try {
c1= Class.forName(className:"reflectdemo.student");
Student student =(student)c1.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);
}
}


// 反射私有属性
public static void reflectPrivateField(){
Class<?> c1;
try {
c1 =Class.forName( className:"reflectdemo.student");
Field field = cl.getDeclaredField(name:"name");//这个方法是获取私有对象
field.setAccessible(true);
Student student=(student)c1.newInstance();
field.set(student,"wangwu");//修改对象的值
System.out.println(student);
}catch(classNotFoundException e){
throw new RuntimeException(e);
}catch(NoSuchFieldException e){
throw new RuntimeException(e);
}catch(InstantiationException e){
throw new RuntimeException(e);
}catch (IllegalAccessException e){
throw new RuntimeException(e);
}
}


// 反射私有方法
public static void reflectPrivateMethod(){
Class<?> c1;
try {
c1 = Class.forName(className:"reflectdemo.Student");
Method method = c1.getDeclaredMethod("function",String.class);
method.setAccessible(true);
Student student(Student)c1.newInstance();
method.invoke(student,.args:"我是一个参数");
//System.out.println(student);
}catch(classNotFoundException e){
throw new RuntimeException(e);
}catch(NoSuchMethodException e){
throw new RuntimeException(e);
}catch(InstantiationException e){
throw new RuntimeException(e);
}catch (IllegalAccessException e){
throw new RuntimeException(e);
}
}

public static void main(string[]args){
//reflectNewInstance();
//reflectPrivateConstructor();
reflectPrivateField();
}
}

反射的优点和缺点

优点:
1.对于任意一个类,都能够知道这个类的所有属性和方法;
对于任意一个对象,都能够调用它的任意一个方法
2.增加程序的**灵活性和扩展性,**降低耦合性,提高自适应能力
3.反射已经运用在了很多流行框架如:Struts、Hibernate、Spring 等等。

缺点:
1.使用反射会有效率问题,会导致程序效率降低
2.反射技术绕过了源代码的技术,因而会带来维护问题。反射代码比相应的直接代码更复杂。

枚举

枚举的使用

public enum TestEnum {
RED,BLACK,GREEN,WHITE;
public static void main(String[] args) {
TestEnum testEnum2 = TestEnum.BLACK;
switch (testEnum2) {
case RED:
System.out.println("red");
break;
case BLACK:
System.out.println("black");
break;
case WHITE:
System.out.println("WHITE");
break;
case GREEN:
System.out.println("black");
break;
default:
break;
}
}
}

枚举的方法

Enum类的常用方法

values() 以数组形式返回枚举类型的所有成员
ordinal() 获取枚举成员的索引位置
valueOf() 将普通字符串转换为枚举实例
compareTo() 比较两个枚举成员在定义时的顺序

注意:枚举的构造方法默认是私有的

枚举优点缺点

优点:

  1. 枚举常量更简单安全 。
  2. 枚举具有内置方法 ,代码更优雅

缺点:
1.不可继承,无法扩展

总结

1、枚举本身就是一个类,其构造方法默认为私有的,且都是默认继承与 java.lang.Enum
2、枚举可以避免反射和序列化问题
3、枚举的优点和缺点

Lambda表达式

函数式接口

要了解Lambda表达式,首先需要了解什么是函数式接口,函数式接口定义:一个接口有且只有一个抽象方法
注意:

  1. 如果一个接口只有一个抽象方法,那么该接口就是一个函数式接口
  2. 如果我们在某个接口上声明了 @FunctionalInterface 注解,那么编译器就会按照函数式接口的定义来要求该接
    口,这样如果有两个抽象方法,程序编译就会报错的。所以,从某种意义上来说,只要你保证你的接口中只
    有一个抽象方法,你可以不加这个注解。加上就会自动进行检测的。
    定义方式:
@FunctionalInterface
interface NoParameterNoReturn {
//注意:只能有一个方法
void test();
}

Lambda表达式的基本使用

//无返回值无参数
@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);
}

Lambda在集合当中的使用

Collection      removeIf() spliterator() stream() parallelStream() forEach()
List          replaceAll() sort()
Map
getOrDefault() forEach() replaceAll() putIfAbsent() remove() replace() computeIfAbsent()
computeIfPresent() compute() merge()

总结

Lambda表达式的优点很明显,在代码层次上来说,使代码变得非常的简洁。缺点也很明显,代码不易读。
优点:

  1. 代码简洁,开发迅速
  2. 方便函数式编程
  3. 非常容易进行并行计算
  4. Java 引入 Lambda,改善了集合操作

缺点:

  1. 代码可读性变差
  2. 在非并行计算中,很多计算未必有传统的 for 性能要高
  3. 不容易进行调试
  • 12
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值