1 反射
定义:Java的反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意方法和属性,既然能拿到,那么我们就可以修改部分类型信息;这种动态获取信息以及动态调用对象方法的功能称为Java语言的反射机制。
1.1 与反射相关的类
类名 | 用途 |
Class类 | 代表类的实体,在运行的Java应用程序中表示类和接口 |
Field类 | 代表类的成员变量/类的属性 |
Method类 | 代表类的方法 |
Constructor类 | 代表类的构造方法 |
1.2代码
package refelectdemo;
class Student{//私有属性nameprivate String name="bit";//共有属性agepublic int age=18;//不带参数的构造方法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 pig");}private void function(String str){System.out.println(str);}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +'}';}
}public class Test {public static void main1(String[] args) throws ClassNotFoundException {//1.获取一个Class对象Class<?> c1=Class.forName("refelectdemo.Student");Class<?> c2=Student.class;//类名.class对象Student student=new Student();Class<?> c3=student.getClass();System.out.println(c1.equals(c2));System.out.println(c1.equals(c3));System.out.println(c2.equals(c3));//Class对象只有一个}
}
package refelectdemo;import com.sun.xml.internal.ws.api.ha.StickyFeature;import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;public class ReflectClassDemo {//创建对象public static void reflectNewInstance(){try{Class<?> c1=Class.forName("refelectdemo.Student");Student student=(Student)c1.newInstance();System.out.println(student);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}//反射私有的构造方法,屏蔽内容为获得公有的构造方法public static void reflectPrivateConstructor(){try{Class<?> c1=Class.forName("refelectdemo.Student");//Constructor<Student> constructor=(Constructor<Student>) c1.getDeclaredConstructor(String.class,int.class);Constructor<?> constructor=c1.getDeclaredConstructor(String.class,int.class);//私有的本身是封装的,constructor.setAccessible(true);Student student=(Student) constructor.newInstance("bit",18);System.out.println(student);}catch (ClassNotFoundException e){} catch (NoSuchMethodException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}//反射所有的,用私有属性来举例public static void reflectPrivateField(){try{Class<?> c1=Class.forName("refelectdemo.Student");Student student=(Student)c1.newInstance();Field field=c1.getDeclaredField("name");field.setAccessible(true);field.set(student,"zhangsan");System.out.println(student);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (NoSuchFieldException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}//反射私有方法public static void reflectPrivateMethod(){try{Class<?> c1=Class.forName("refelectdemo.Student");Student student=(Student)c1.newInstance();//方法名称 方法的参数Method method=c1.getDeclaredMethod("function",String.class);method.setAccessible(true);method.invoke(student,"我是function的参数");} catch (ClassNotFoundException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}}public static void main(String[] args) {//reflectNewInstance();//reflectPrivateConstructor();//reflectPrivateField();reflectPrivateMethod();}
}
2 枚举
Enum类的常用方法
方法名称 | 描述 |
values() | 以数组形式返回枚举类型的所有成员 |
ordinal() | 获取枚举成员的索引位置 |
valueOf() | 将普通字符串转换为枚举实例 |
compareTo() | 比较两个枚举成员在定义时的顺序 |
1.1 代码
package enumdemo;
//自己写的枚举类,都默认继承于Enum
public enum TestEnum {RED("红色",1),GREEN("绿色",2),BLACK("黑色",3);//枚举对象public String color;public int ordinal;//枚举的构造方法默认是私有的private TestEnum(String color, int ordinal) {this.color = color;this.ordinal = ordinal;}public static void main(String[] args) {TestEnum[] array =TestEnum.values();for (int i=0;i<array.length;i++){System.out.println(array[i]+" "+array[i].ordinal());}System.out.println("============");TestEnum test=TestEnum.valueOf("RED");System.out.println(test);System.out.println("=================");System.out.println(RED.compareTo(BLACK));}public static void main1(String[] args) {TestEnum testEnum2=TestEnum.BLACK;switch (testEnum2){case RED:System.out.println("red");break;case GREEN:System.out.println("green");break;case BLACK:System.out.println("black");break;default:break;}}
}
1.2 枚举的优缺点
- 优点:枚举常量更简单安全;枚举具有内置方法,代码更优雅
- 缺点:不可继承,无法扩展
package enumdemo;import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;public class TestReflectEnum {public static void func(){try{Class<?> c=Class.forName("enumdemo.TestEnum");Constructor<?> constructor=c.getDeclaredConstructor(String.class,int.class,String.class,int.class);constructor.setAccessible(true);TestEnum testEnum=(TestEnum)constructor.newInstance("草原色",89);System.out.println(testEnum);} catch (ClassNotFoundException e) {e.printStackTrace();} catch (NoSuchMethodException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();} catch (InstantiationException e) {e.printStackTrace();} catch (IllegalAccessException e) {e.printStackTrace();}}public static void main(String[] args) {func();}
}
3 Lambda表达式
缺点:不易读
优点:代码量少
package 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{void test(int a);
}//有返回值多个参数
@FunctionalInterface
interface MoreParameterReturn{int test(int a, int b);
}public class Test1 {public static void main(String[] args) {NoParameterReturn noParameterReturn=()->{return 10;};NoParameterReturn noParameterReturn1=()->10;int ret=noParameterReturn1.test();System.out.println(ret);}public static void main2(String[] args) {NoParameterNoReturn noParameterNoReturn=()->{System.out.println("haha");};noParameterNoReturn.test();//一条语句花括号省略OneParameterNoReturn oneParameterNoReturn=a-> System.out.println(a);OneParameterNoReturn oneParameterNoReturn2=(a)-> {System.out.println(a);};oneParameterNoReturn.test(10);MoreParameterNoReturn moreParameterNoReturn=(a,b)->{System.out.println(a+b);};//如果方法体只有一条语句,花括号可以省略MoreParameterNoReturn moreParameterNoReturn1=(a,b)-> System.out.println(a+b);moreParameterNoReturn.test(1,2);}public static void main1(String[] args) {MoreParameterReturn moreParameterReturn=new MoreParameterReturn(){@Overridepublic int test(int a, int b) {return a+b;}};MoreParameterReturn moreParameterReturn2=(int a,int b)->{return a+b;};}
}