赞
踩
目录
类名
|
用途
|
Class
类
|
代表类的实体,在运行的
Java
应用程序中表示类和接口
|
Field
类
|
代表类的成员变量
/
类的属性
|
Method类
|
代表类的方法
|
Constructor类 |
代表类的构造方法
|
方法
|
用途
|
getClassLoader()
|
获得类的加载器
|
getDeclaredClasses()
|
返回一个数组,数组中包含该类中所有类和接口类的对象
(
包括私有的
)
|
forName(String className)
|
根据类名返回类的对象
|
newInstance()
|
创建类的实例
|
getName()
|
获得类的完整路径名字
|
方法 | 用途 |
getField(String name)
|
获得某个公有的属性对象
|
getFields()
|
获得所有公有的属性对象
|
getDeclaredField(String name)
|
获得某个属性对象
|
getDeclaredFields()
|
获得所有属性对象
|
方法 | 用途 |
getMethod(String name, Class...<?> parameterTypes)
|
获得该类某个公有的方法
|
getMethods()
|
获得该类所有公有的方法
|
getDeclaredMethod(String name, Class...<?> parameterTypes)
|
获得该类某个方法
|
getDeclaredMethods() |
获得该类所有方法
|
方法 | 用途 |
getConstructor(Class...<?> parameterTypes)
|
获得该类中与参数类型匹配的公有构造方法
|
getConstructors()
|
获得该类的所有公有构造方法
|
getDeclaredConstructor(Class...<?> parameterTypes)
|
获得该类中与参数类型匹配的构造方法
|
getDeclaredConstructors()
|
获得该类所有构造方法
|
方法 | 用途 |
getAnnotation(Class
annotationClass)
|
返回该类中与参数类型匹配的公有注解对象
|
getAnnotations()
|
返回该类所有的公有注解对象
|
getDeclaredAnnotation(Class
annotationClass)
|
返回该类中与参数类型匹配的所有注解对象
|
getDeclaredAnnotations()
|
返回该类所有的注解对象
|
- package reflect;
-
- class Student{
- //私有属性name
- private String name = "bit";
- //公有属性age
- public 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 a pig");
- }
- private void function(String str) {
- System.out.println(str);
- }
-
- @Override
- public String toString() {
- return "Student{" +
- "name='" + name + '\'' +
- ", age=" + age +
- '}';
- }
- }
- public class TestDemo2 {
- public static void main(String[] args) throws ClassNotFoundException{
- Class<?> c1 = Class.forName("reflect.Student");
-
- Class<?> c2 = Student.class;
-
- Student student = new Student();
- Class<?> c3 = student.getClass();
-
- System.out.println(c1 == c2);
- System.out.println(c1 == c3);
- System.out.println(c2 == c3);
- //全部都是true,说明不管使用哪种方式获取Class对象,该对象只有一个
- }
- }
(以下代码与上面的代码在同一个包底下)
- package reflect;
-
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Field;
- import java.lang.reflect.InvocationTargetException;
- import java.lang.reflect.Method;
-
- public class ReflectClassDemo {
- //通过Class类的newInstance方法获取学生的一个实例
- public static void reflectNewInstance() {
- try{
- Class<?> c1 = Class.forName("reflect.Student");
- Student student = (Student) c1.newInstance();//newInstance()的返回值是T类型
- 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("reflect.Student");
- Constructor<?> constructor = c1.getDeclaredConstructor(String.class, int.class);
- constructor.setAccessible(true);
- Student student = (Student)constructor.newInstance("abc",18);
- System.out.println(student);
- } 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 reflectPrivateField() {
- try {
- Class<?> c1 = Class.forName("reflect.Student");
- Student student = (Student) c1.newInstance();
- Field field = c1.getDeclaredField("name");
- field.setAccessible(true);
- field.set(student,"zhangssan");
- System.out.println(student);
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (InstantiationException e) {
- e.printStackTrace();
- } catch (IllegalAccessException e) {
- e.printStackTrace();
- } catch (NoSuchFieldException e) {
- e.printStackTrace();
- }
- }
- //反射私有的方法
- public static void reflectPrivateMethod() {
- try {
- Class<?> c1 = Class.forName("reflect.Student");
- Student student = (Student) c1.newInstance();
- Method method = c1.getDeclaredMethod("function", String.class);
- method.setAccessible(true);
- method.invoke(student,"我是私有方法的参数");
- } 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();
- }
- }
- public static int final RED = 1;
- public static int final GREEN = 2;
- public static int final BLACK = 3;
- public enum TestEnum {
- RED,BLACK,GREEN;
- }
(1)switch语句里面:
- 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;
- }
- }
- }
方法名称 | 描述 |
values()
|
以数组形式返回枚举类型的所有成员
|
ordinal()
|
获取枚举成员的索引位置
|
valueOf()
|
将普通字符串转换为枚举实例
|
compareTo()
|
比较两个枚举成员在定义时的顺序
|
- public enum TestEnum {
- RED,BLACK,GREEN,WHITE;
-
- public static void main(String[] args) {
- TestEnum[] testEnums = TestEnum.values();
- for (int i = 0; i < testEnums.length; i++) {
- System.out.println(testEnums[i] + "-->" + testEnums[i].ordinal());
- }
- }
- }
- public enum TestEnum {
- RED,BLACK,GREEN,WHITE;
-
- public static void main(String[] args) {
- TestEnum testEnum = TestEnum.valueOf("RED");//把字符串变成对应的枚举对象
- System.out.println(testEnum);//RED
- System.out.println(RED.compareTo(GREEN));//-2
- System.out.println(BLACK.compareTo(RED));//1
- }
- }
(3)枚举的构造方法默认是私有的
- public enum TestEnum {
- RED("red",1),BLACK(),GREEN,WHITE;//它属于对象,当我们在它们后面加括号后相当于调用构造方法了
-
- public String color;
- public int ordinal;
- //构造方法默认是私有的
- TestEnum(String color,int ordinal){
- this.color = color;
- this.ordinal = ordinal;
- }
- TestEnum(){
-
- }
- }
既然枚举的构造方法是私有的,那么是否可以通过反射来获取到枚举对象的实例呢?
- package enumdemo;
-
- public enum TestEnum {
- RED("red",1),BLACK("black",3),GREEN("green",8), WHITE("white",2);
-
- public String color;
- public int ordinal;
- //构造方法默认是私有的
- TestEnum(String color,int ordinal){
- //super();
- this.color = color;
- this.ordinal = ordinal;
- }
- }
- package enumdemo;
-
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
-
- public class TestEnumReflect {
- public static void reflectPrivateConstructor(){
- try{
- Class<?> classEnum = Class.forName("enumdemo.TestEnum");
- Constructor<?> declaredConstructorStudent =
- classEnum.getDeclaredConstructor(String.class,int.class);
- declaredConstructorStudent.setAccessible(true);
- Object objectStudent = declaredConstructorStudent.newInstance("green",666);
- TestEnum testEnum = (TestEnum) objectStudent;
- 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) {
- reflectPrivateConstructor();
- }
- }
编译并运行该代码,输出如下:
那么现在我们来修改一下它吧!
- package enumdemo;
-
- import java.lang.reflect.Constructor;
- import java.lang.reflect.InvocationTargetException;
-
- public class TestEnumReflect {
- public static void reflectPrivateConstructor(){
- try{
- Class<?> classEnum = Class.forName("enumdemo.TestEnum");
- Constructor<?> declaredConstructorStudent =
- classEnum.getDeclaredConstructor(String.class,int.class,String.class,int.class);
- declaredConstructorStudent.setAccessible(true);
- Object objectStudent = declaredConstructorStudent.newInstance("green",666,"abc",999);
- TestEnum testEnum = (TestEnum) objectStudent;
- 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) {
- reflectPrivateConstructor();
- }
- }
编译并运行该代码,输出如下:
它还在报错,这是为什么呢?我们来看一下部分底层的源码:
这说明:枚举十分安全,不能通过反射来获取枚举的实例对象
总结:
①枚举本身就是一个类,其构造方法默认为私有的,且都是默认继承与 java.lang.Enum
②枚举可以避免反射和序列化问题
写一个单例模式
(1)普通实现
- public class Singleton {
- private volatile static Singleton uniqueInstance;
- private Singleton() {}
- public static Singleton getInstance() {
- if (uniqueInstance == null) {
- synchronized (Singleton.class){
- if(uniqueInstance == null){//进入区域后,再检查一次,如果仍是null,才创建实例
- uniqueInstance = new Singleton();
- }
- }
- }
- return uniqueInstance;
- }
- }
(2)用静态内部类实现一个单例模式
- class Singleton { /** 私有化构造器 */
- private Singleton() { }/** 对外提供公共的访问方法 */
- public static Singleton getInstance() {
- return UserSingletonHolder.INSTANCE;
- }/** 写一个静态内部类,里面实例化外部类 */
- private static class UserSingletonHolder {
- private static final Singleton INSTANCE = new Singleton();
- }
- }
- public class Main {
- public static void main(String[] args) {
- Singleton u1 = Singleton.getInstance();
- Singleton u2 = Singleton.getInstance();
- System.out.println("两个实例是否相同:"+ (u1==u2));
- }
- }
(3)用枚举实现一个单例模式
- public enum TestEnum {
- INSTANCE; public TestEnum getInstance(){
- return INSTANCE;
- }
- public static void main(String[] args) {
- TestEnum singleton1=TestEnum.INSTANCE;
- TestEnum singleton2=TestEnum.INSTANCE;
- System.out.println("两个实例是否相同:"+(singleton1==singleton2));
- }
- }
- package lambdademo;
-
- //函数式接口(只有一个抽象方法)
- @FunctionalInterface//这个注释修饰这个接口,说明它是函数式接口
- interface NoParameterNoReturn{
- void test();
- }
- public class TestDemo {
- public static void main(String[] args) {
- //简化的写法
- NoParameterNoReturn noParameterNoReturn = () -> System.out.println("重写方法!");
- noParameterNoReturn.test();
- }
- public static void main1(String[] args) {
- NoParameterNoReturn noParameterNoReturn = new NoParameterNoReturn(){
- @Override
- public void test(){
- System.out.println("重写方法!");
- }
- };
- noParameterNoReturn.test();
- }
- }
- //没有返回值,没有参数
- @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 class TestDemo {
- public static void main(String[] args) {
- OneParameterNoReturn oneParameterNoReturn = (a) ->{System.out.println(a);};
- oneParameterNoReturn.test(10);
- //优化
- OneParameterNoReturn oneParameterNoReturn2 = a ->System.out.println(a);
- oneParameterNoReturn.test(10);
- //继续优化
- OneParameterNoReturn oneParameterNoReturn3 = System.out::println;
- oneParameterNoReturn.test(10);
-
- MoreParameterNoReturn moreParameterNoReturn = (a,b) -> {//理论上来说要写(int a,int b)但是因为a,b同类型,所以两个int都可以省略
- System.out.println(a+b);
- };
- moreParameterNoReturn.test(10,20);
-
- NoParameterReturn noParameterReturn = () -> {return 10;};
- int ret = noParameterReturn.test();
- System.out.println(ret);
- //简写:
- NoParameterReturn noParameterReturn2 = () -> 10;
- int ret2 = noParameterReturn2.test();
- System.out.println(ret2);
-
- OneParameterReturn oneParameterReturn = a -> a + 11;
- System.out.println(oneParameterReturn.test(10));
-
- MoreParameterReturn moreParameterReturn = (a,b) -> a+b;
- System.out.println(moreParameterReturn.test(1,2));
- }
- }
- package lambdademo;
-
- class Test {
- public void func(){
- System.out.println("func()");
- }
- }
- public class TestDemo2 {
- public static void main(String[] args) {
- int a = 100;
- //a = 99;//error
- new Test() {
- @Override
- public void func() {
- System.out.println("我是内部类,且重写了func这个方法!");
- System.out.println("我是捕获到变量 a == " + a + " 我要么是一个常量,要么是一个没有改变过值的变量!");
- }
- }.func();
- }
- }
对应的接
口
|
新增的方法
|
Collection
|
removeIf() spliterator()
stream()
parallelStream()
forEach()
|
List
|
replaceAll()
sort()
|
Map
|
getOrDefault() forEach()
replaceAll() putIfAbsent() remove() replace() computeIfAbsent() computeIfPresent() compute() merge()
|
forEach() 方法演示:
该方法在接口 Iterable 当中,原型如下:
- default void forEach(Consumer<? super T> action) {
- Objects.requireNonNull(action);
- for (T t : this) {
- action.accept(t);
- }
- }
该方法表示:对容器中的每个元素执行action指定的动作 。
演示如下:
- package lambdademo;
-
- import java.util.ArrayList;
- import java.util.function.Consumer;
-
- public class TestDemo2 {
- public static void main(String[] args) {
- ArrayList<String> list = new ArrayList<>();
- list.add("Hello");
- list.add("bit");
- list.add("hello");
- list.add("lambda");
- /*list.forEach(new Consumer<String>(){
- @Override
- public void accept(String str){ //简单遍历集合中的元素。
- System.out.print(str+" ");
- }
- });*/
- //等价于
- list.forEach(str -> System.out.print(str + " "));
- }
- }
- public void sort(Comparator<? super E> c) {
- final int expectedModCount = modCount;
- Arrays.sort((E[]) elementData, 0, size, c);
- if (modCount != expectedModCount) {
- throw new ConcurrentModificationException();
- }
- modCount++;
- }
演示如下:
- package lambdademo;
-
- import java.util.ArrayList;
- import java.util.Comparator;
-
- public class TestDemo2 {
- public static void main(String[] args) {
- ArrayList<String> list = new ArrayList<>();
- list.add("zello");
- list.add("bit");
- list.add("hello");
- list.add("lambda");
- list.forEach(str -> System.out.print(str + " "));
- System.out.println();
- System.out.println("====================");
- //list.sort((o1,o2) -> o1.compareTo(o2));
- //等价于:
- list.sort(new Comparator<String>() {
- @Override
- public int compare(String o1, String o2) {
- return o1.compareTo(o2);
- }
- });
- list.forEach(str -> System.out.print(str + " "));
- }
- }
编译并运行该代码,输出如下:
演示如下:
- package lambdademo;
-
- import java.util.ArrayList;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.function.BiConsumer;
-
- class Test {
- public void func(){
- System.out.println("func()");
- }
- }
- public class TestDemo2 {
- public static void main(String[] args) {
- HashMap<Integer, String> map = new HashMap<>();
- map.put(1, "hello");
- map.put(2, "bit");
- map.put(3, "hello");
- map.put(4, "lambda");
- map.forEach(new BiConsumer<Integer, String>(){
- @Override
- public void accept(Integer key, String value){
- System.out.print(key + "=" + value + " ");
- }
- });
- //简化(使用lambda表达式)
- System.out.println();
- System.out.println("====================");
- map.forEach((k,v)-> System.out.print(k + "=" + v+" "));
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。