------Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
反射
主要内容:《获取Class对象的三种方式、获取无参_有参构造方法、获取成员变量、获取成员方法、运行配置文件内容、越过泛型检查、代理模式、动态代理、模版设计模式、装饰模式、 JDK5的新特性、JDK7的新特性 》
1.获取Class对象的三种方式
1.Object类中的:getClass():此方法不是静态的,必须对象的引用调用;
2.class属性:任何的数据类型(包括基本数据类型)都有一个静态的class属性,它可以获取这个类的Class对象;
3.Class类中有个静态方法:
Class forName(String className);className要是全名限定的类名(带包名的类名)
常用:第3种;
1 public class Demo {
2 public static void main(String[] args) throws ClassNotFoundException {
3 Student stu = new Student();//会产生:Student对象空间,Class对象空间
4 //方式一:获取Class对象
5 Class stuClass1 = stu.getClass();
6 //方式二:静态的class属性
7 Class stuClass2 = Student.class;
8 // Class intClass = int.class;//基本数据类型也有
9 System.out.println("stuClass1 == stuClass2 : " + (stuClass1 == stuClass2));
10
11 //方式三:Class的静态方法forName()
12 // Class stuClass3 = Class.forName("Student");//运行时异常:java.lang.ClassNotFoundException
13 Class stuClass3 = Class.forName("cn.itcast.demo01_获取Class对象的三种方式.Student");
14 System.out.println("stuClass1 == stuClass3 : " + (stuClass1 == stuClass3));
15
16 }
17 }
18 public class Student {
19 private String name;
20 }
2.通过反射获取无参_有参构造方法并使用
通过反射获取无参_有参构造方法并使用:
Class:
//---批量的;
Constructor[] getConstructors():获取所有的"公有"构造方法;
Constructor[] getDeclaredConstructors()::获取所有的(包括私有的)构造方法;
每一个Constructor内部都包含了"一个构造方法"的详细信息;
//---获取某个Constructor对象
public Constructor getConstructor(Class ... parameterTypes):获取某个公有的构造方法
public Constructor getDeclaredConstructor(Class<?>... parameterTypes):获取某个构造方法(包括私有的)
//Constructor的成员方法:
public Object newInstance(Object... initargs):创建这个Class类所表示的类的一个对象;
1 public class Demo {
2 public static void main(String[] args) throws Exception{
3 //*********获取Class对象************//
4 Class stuClass = Class.forName("cn.itcast.demo02_通过反射获取无参_有参构造方法并使用.Student");
5 //*********获取所有的"公有的"构造方法*********
6 Constructor[] conArray = stuClass.getConstructors();
7 //遍历
8 System.out.println("**********所有 公共的 构造方法***********");
9 for(Constructor c : conArray){
10 System.out.println(c);
11 }
12
13 //********获取所有的构造方法***********//
14 System.out.println("**********所有构造方法(包括私有)***********");
15 conArray = stuClass.getDeclaredConstructors();
16 for(Constructor c : conArray){
17 System.out.println(c);
18 }
19 /*
20 * class Class{
21 * public Constructor getConstructor(){
22 * return new Constructor();
23 * }
24 * }
25 * class Constructor{
26 * }
27 */
28 System.out.println("**********获取单个,公有,无参的构造方法,并调用***********");
29 Constructor con = stuClass.getConstructor();//获取无参的
30 Object obj = con.newInstance();
31 System.out.println("obj = " + obj);
32 System.out.println("**********获取单个,公有,带参的构造方法,并调用***********");
33 con = stuClass.getConstructor(int.class);//获取int参数的公有构造方法
34 con.newInstance(20);//20就是"实参",使用这个实参去调用此构造方法
35
36 System.out.println("**********获取私有,带参的构造方法,并调用***********");
37 con = stuClass.getDeclaredConstructor(String.class,boolean.class);
38 con.setAccessible(true);//如果是私有的,设置暴力访问
39 con.newInstance("刘德华",false);
40
41
42
43 }
44 }
1 public class Student {
2 //************构造方法************//
3 //公有无参
4 public Student(){
5 System.out.println("Student类的公有,无参的构造方法被执行......");
6 }
7 //公有带参
8 public Student(int n){
9 System.out.println("Student类的公有,带参的构造方法被执行,n = " + n);
10 }
11
12 //受保护的
13 protected Student(String s){
14 System.out.println("Student类的受保护的构造方法被执行,s = " + s);
15 }
16
17 //默认的
18 Student(char c){
19 System.out.println("Student类的默认的构造方法被执行, c = " + c);
20 }
21 //私有的
22 private Student(String s ,boolean b){
23 System.out.println("Student类的私有的构造方法被执行,s = " + s + ",b = " + b);
24 }
25 }
3.通过反射获取成员变量并使用
通过反射获取成员变量并使用
Class类:
----批量的:
Field[] getFields():获取所有公有的成员变量
Field[] getDeclaredFields():获取所有成员变量(包括私有)
----单个的:
Field getField():获取单个,公有的成员变量
Field getDeclaredField():获取单个的成员变量,包括私有的
----为成员变量赋值:
Filed --> set(Object obj,Object value)
1 public class Demo {
2 public static void main(String[] args) throws Exception {
3 //1.获取Class对象
4 Class stuClass = Class.forName("cn.itcast.demo03_通过反射获取成员变量并使用.Student");
5 System.out.println("*********获取所有公有的成员变量************");
6 Field[] fieldArray = stuClass.getFields();
7 for(Field f : fieldArray){
8 System.out.println(f);
9 }
10 System.out.println("*********获取所有的成员变量(包括私有的)************");
11 fieldArray = stuClass.getDeclaredFields();
12 for(Field f : fieldArray){
13 System.out.println(f);
14 }
15 System.out.println("*********获取单个公有的成员变量,并赋值************");
16 Field f = stuClass.getField("name");
17 //赋值前,一定要确保堆中有"对象空间",所有要先创建一个对象
18 Object obj = stuClass.getConstructor().newInstance();//调用公有无参的构造方法
19 f.set(obj, "刘德华");
20
21 System.out.println("*********获取私有的成员变量,并赋值*********************");
22 f = stuClass.getDeclaredField("address");
23 f.setAccessible(true);//设置暴力访问
24 f.set(obj, "北京市");
25 //验证
26 Student stu = (Student)obj;
27 System.out.println("Student的 name = " + stu.name + " address = " + stu.getAddress());
28
29
30
31 }
32 }
1 public class Student {
2 //*********成员变量**********//
3 public String name;
4 protected int age;
5 char sex;
6 private String address;
7
8 public String getAddress(){
9 return this.address;
10 }
11
12
13 }
4.通过反射获取成员方法并使用
获取成员方法:
Class类的:
----批量的:
Method[] getMethods():获取所有公有的成员方法;
Method[] getDeclaredMethods():获取所有的成员方法包括私有的。
----单个:
Method getMethod():获取单个公有的成员方法;
Method getDeclaredMethod():获取单个成员方法,包括私有的;
----调用方法:
Method --> public Object invoke(Object obj,Object... args)
1 public class Demo {
2 public static void main(String[] args) throws Exception{
3 //1.获取Class对象
4 Class stuClass = Class.forName("cn.itcast.demo04_通过反射获取成员方法并使用.Student");
5 System.out.println("*****************************获取所有公有的成员方法*****************************");
6 Method[] methodArray = stuClass.getMethods();//包含了父类的公有的
7 for(Method m : methodArray){
8 System.out.println(m);
9 }
10
11 System.out.println("*****************************获取所有的成员方法(包括私有的)*****************************");
12 methodArray = stuClass.getDeclaredMethods();//不包含继承的;
13 for(Method m : methodArray){
14 System.out.println(m);
15 }
16 System.out.println("*****************************获取单个公有的,无参的并调用*****************************");
17 Method m = stuClass.getMethod("show1");
18 //实例化一个对象
19 Object obj = stuClass.newInstance();
20 m.invoke(obj);
21
22 System.out.println("*****************************获取单个公有的,带参的,带返回值并调用*****************************");
23
24 m = stuClass.getMethod("show2", String.class,int.class);
25 Object result = m.invoke(obj, "张三",20);//传递实参,并接受返回值;
26 System.out.println("返回值为:" + result);
27
28 System.out.println("*****************************获取单个私有的,带参的并调用*****************************");
29 m = stuClass.getDeclaredMethod("show5", int.class);
30 m.setAccessible(true);//暴力访问
31 m.invoke(obj, 20);
32
33 }
34 }
1 public class Student {
2 public void show1(){
3 System.out.println("公有的,无参的show1()方法......");
4 }
5 public int show2(String s,int n){
6 System.out.println("公有 show2()方法:s = " + s + " , n = " + n );
7 return 1000;
8 }
9
10 protected void show3(int n){
11 System.out.println("受保护的show3()方法:n = " + n);
12 }
13
14 void show4(int n){
15 System.out.println("默认的show4()方法:n = " + n);
16 }
17 private void show5(int n){
18 System.out.println("私有的show5()方法:n = " + n);
19 }
20 }
5.通过反射运行配置文件内容
1 public class Demo {
2 public static void main(String[] args) throws Exception{
3 /*Student stu = new Student();
4 stu.show();*/
5
6 //后期升级,Student类需要改为:Teacher,
7 // show()方法需要改为:fun()方法;
8 //1.新建Teacher类,并添加fun()方法;
9 //2.此Demo类中的代码需要修改;
10
11 //为了在更新程序时,避免修改其它已有的源码,可以使用:"反射机制"
12 // Class stuClass = Class.forName("cn.itcast.demo05_通过反射运行配置文件内容.Student");
13 //1.建立配置文件;
14 //2.在配置文件中,建立:键值对;
15 //3.此处,使用"键名";获取相应的"值"
16 Class stuClass = Class.forName(getValue("className"));//"cn.itcast.demo05_通过反射运行配置文件内容.Student"
17 //获取Method对象
18 // Method m = stuClass.getMethod("show");
19 Method m = stuClass.getMethod(getValue("methodName"));//show
20 //调用show()方法
21 m.invoke(stuClass.newInstance());
22
23
24 }
25 //此方法,从配置文件中,根据某个key获取对应的value
26 private static String getValue(String key) throws IOException{
27 FileReader in = new FileReader("my.properties");
28 Properties pro = new Properties();
29 //读取配置文件
30 pro.load(in);
31 in.close();
32
33 return pro.getProperty(key);
34
35 }
36 }
37
38 public class Student {
39 public void show(){
40 System.out.println("is show()");
41 }
42 }
43
44 public class Teacher {
45 public void fun(){
46 System.out.println(" Teacher--> fun()");
47 }
48 }
6.通过反射越过泛型检查
1 import java.lang.reflect.Method;
2 import java.util.ArrayList;
3
4 /*
5 * 通过反射越过泛型检查
6 *
7 * 1.有一个具有String泛型的ArrayList,问:怎么可以向集合中添加一个数字:
8 *
9 *
10 */
11 public class Demo {
12 public static void main(String[] args) throws Exception{
13 ArrayList<String> strList = new ArrayList<>();
14 // strList.add(20);
15
16 //泛型,只在"编译期",生成class后,泛型就没有了
17 //1.获取ArrayList的Class对象
18 Class listClass = strList.getClass();
19 //2.获取add()方法
20 Method addMethod = listClass.getMethod("add", Object.class);
21 //3.调用Method对象的方法,执行add()方法
22 addMethod.invoke(strList, 20);
23 addMethod.invoke(strList, 30);
24 addMethod.invoke(strList, "abc");
25
26 //测试:遍历strList
27 for(Object obj : strList){
28 System.out.println(obj);
29 }
30
31 }
32 }
7.写一个通用的设置某个对象的某个属性为指定的值
1 import java.lang.reflect.Field;
2
3 /*
4 * 写一个通用的设置某个对象的某个属性为指定的值的方法
5 *
6 * 1.写一个通用的方法
7 * 2.可以:对某个对象,的某个属性,赋值为某个值
8 */
9 public class Demo {
10 public static void main(String[] args) throws Exception {
11
12 Cat cat = new Cat();
13 //为cat对象的name属性赋值为:波斯猫
14 setValue(cat,"name","波斯猫");
15
16 //测试
17 cat.print();
18
19 Dog d = new Dog();
20 //为dog对象的color属性设置为:白色
21 setValue(d,"color","白色");
22 //测试
23 d.print();
24 }
25 public static void setValue(Object obj, String fieldName, Object value)
26 throws Exception {
27 // 1.获取obj的Class对象
28 Class c = obj.getClass();
29 // 2.获取Field对象
30 Field f = c.getDeclaredField(fieldName);
31 // Field对象所代表的字段,可能是private私有的
32 //设置暴力访问
33 f.setAccessible(true);
34 //3.设置
35 f.set(obj, value);
36
37 }
38 }
39
40 public class Cat {
41 private String name;
42
43 public void print(){
44 System.out.println("Cat name = " + name);
45 }
46 }
47
48 public class Dog {
49 private String color;
50
51 public void print(){
52 System.out.println("Dog color = " + color);
53 }
54 }
8.代理模式
1.在不改变原类的基础上,可以为原类增加一些其他功能;
2.当有代理后,我们可以直接面对:代理类
有一个类,访问数据库中的Student表:
class StudentService{
public void add(){
//添加一条Student信息;
}
public void delete(){
//删除数据库中一条Student信息;
}
}
现在要求,在不更改原类的基础上,在调用这两个方法时,都要做两个操作:
1.在调用此方法之前:检查:是否有权限;
2.在调用此方法之后:写日志;
建立一个"代理类",后期使用,直接使用此代理类;
缺陷:如果其它类,也需要加这两个方法,也得添加代理类,这样会导致类太多;
1 public class Demo {
2 public static void main(String[] args) {
3 /*StudentService stuService = new StudentService();
4 stuService.add();
5 stuService.delete();*/
6
7 //直接面对代理
8 StudentServiceProxy proxy = new StudentServiceProxy();
9 proxy.add();
10 proxy.delete();
11 }
12 }
13
14 public class StudentService {
15 public void add(){
16 System.out.println("添加一条数据......");
17 }
18 public void delete(){
19 System.out.println("删除一条数据......");
20 }
21 }
22
23 public class StudentServiceProxy {
24 private StudentService stuService = new StudentService();
25
26 public void add(){
27 check();
28 stuService.add();
29 log();
30 }
31 public void delete(){
32 check();
33 stuService.delete();
34 log();
35 }
36
37 private void check(){
38 System.out.println("先期进行权限检查......");
39 }
40 private void log(){
41 System.out.println("后期进行记录日志.....");
42 }
43
44
45 }
9.动态代理的概述和实现
之前的代理模式有个缺陷,如果其它类也需要增加那两个操作,也必须要增加一个代理类,
这样使用起来比较麻烦;
Java中提供了"动态代理":不需要"代理类",动态代理机制会为要代理的类,自动产生一个代理对象;
Java中的动态代理是基于"接口"的,需要代理的类,一定要是某个接口的实现类;
步骤:
1.定义一个类,实现:InvocationHandler
2.在使用时,使用Proxy:newProxyInstance()方法产生代理对象;
1 public class Demo {
2 public static void main(String[] args) {
3 IService stuService = (IService)Proxy.newProxyInstance(
4 StudentService.class.getClassLoader(),
5 StudentService.class.getInterfaces(),
6 new MyInvocationHandler(new StudentService())
7 );
8
9
10 stuService.add();
11 stuService.delete();
12
13 IService teaService = (IService)Proxy.newProxyInstance(TeacherService.class.getClassLoader(),
14 TeacherService.class.getInterfaces(),
15 new MyInvocationHandler(new TeacherService()));
16 teaService.add();
17 teaService.delete();
18
19
20 }
21 }
1 public interface IService {
2 public void add();
3 public void delete();
4 }
1 import java.lang.reflect.InvocationHandler;
2 import java.lang.reflect.Method;
3
4 public class MyInvocationHandler implements InvocationHandler {
5 //要代理的对象;
6 private Object target;
7
8 //通过构造方法赋值
9 public MyInvocationHandler(Object obj){
10 this.target = obj;
11 }
12
13 @Override
14 public Object invoke(Object proxy, Method method, Object[] args)
15 throws Throwable {
16 this.check();
17 //调用应该调用的方法;
18 Object result = method.invoke(this.target, args);
19 this.log();
20 //返回方法调用的结果
21 return result;
22 }
23
24 //为代理对象额外添加的操作
25 private void check(){
26 System.out.println("先期进行权限检查......");
27 }
28 private void log(){
29 System.out.println("后期进行记录日志.....");
30 }
31
32 }
1 public class StudentService implements IService{
2 public void add(){
3 System.out.println("添加一条数据......");
4 }
5 public void delete(){
6 System.out.println("删除一条数据......");
7 }
8
9 }
1 public class TeacherService implements IService{
2
3 @Override
4 public void add() {
5 System.out.println("添加一条Teacher信息......");
6 }
7
8 @Override
9 public void delete() {
10 System.out.println("删除一条Teacher信息......");
11 }
12
13 }
10.模版设计模式概述和使用
1 abstract class Person{
2 //模板方法
3 void show(){
4 System.out.println("我是传智播客的一名 " + getType() + " ,我骄傲!!");
5 }
6 abstract String getType();
7 }
8 class Student extends Person{
9 @Override
10 String getType() {
11 return "学生";
12 }
13 }
14 class Teacher extends Person{
15 @Override
16 String getType() {
17 return "教师";
18 }
19 }
20 public class Demo {
21 public static void main(String[] args) {
22 Student stu = new Student();
23 stu.show();//show()是继承的
24
25 Teacher tea = new Teacher();
26 tea.show();//
27 }
28 }
11.装饰模式
1 public static void main(String[] args) {
2 //我们可以直接使用具体的产品
3 /*ThinkPadX240 x240 = new ThinkPadX240();
4 x240.sellComputer();
5
6 ThinkPadX550 x550 = new ThinkPadX550();
7 x550.sellComputer();*/
8
9 //我们去西三旗经销商那里去买
10
11
12 ThinkPad_XSQ_Dealer xsq = new ThinkPad_XSQ_Dealer(new ThinkPadX240());
13 xsq.sellComputer();
14
15 //去中关村买
16 ThinkPad_ZGC_Dealer zgc = new ThinkPad_ZGC_Dealer(new ThinkPadX550());
17 zgc.sellComputer();
18 System.out.println("-------------------------------------");
19 IThinkPad think = new ThinkPad_XSQ_Dealer(new ThinkPad_ZGC_Dealer(new ThinkPadX240()));
20 think.sellComputer();
21
22 }
23 }
24
25 public abstract class AbstractThinkPadDealer implements IThinkPad{
26 private IThinkPad think;
27
28 public AbstractThinkPadDealer(IThinkPad think){
29 this.think = think;
30 }
31
32 @Override
33 public void sellComputer() {
34 this.think.sellComputer();
35 }
36
37
38 }
39
40 public interface IThinkPad {
41 void sellComputer();
42 }
43
44 public class ThinkPad_XSQ_Dealer extends AbstractThinkPadDealer {
45
46 public ThinkPad_XSQ_Dealer(IThinkPad think) {
47 super(think);
48 }
49 public void sellComputer(){
50 super.sellComputer();
51 System.out.println("西三旗经销商,赠送一套三居室......");
52
53 }
54
55 }
56
57 public class ThinkPad_ZGC_Dealer extends AbstractThinkPadDealer {
58
59 public ThinkPad_ZGC_Dealer(IThinkPad think) {
60 super(think);
61 }
62
63 public void sellComputer(){
64 super.sellComputer();
65 System.out.println("中关村经销商,赠送一辆劳斯莱斯......");
66 }
67
68 }
69
70 public class ThinkPadX240 implements IThinkPad {
71 @Override
72 public void sellComputer() {
73 System.out.println("ThinkPadX240部门:卖一台X240");
74 }
75
76 }
77
78 public class ThinkPadX550 implements IThinkPad {
79
80 @Override
81 public void sellComputer() {
82 System.out.println("ThinkPadX550部门:卖一台X550");
83 }
84
85 }
12.JDK5的新特性
1 import java.util.ArrayList;
2
3 /*
4 * JDK5的新特性:
5 * 自动装箱和拆箱:
6 泛型:
7 增强for循环:
8 静态导入:
9 可变参数:
10 枚举
11
12 */
13 //静态导入:导入某个类中的静态方法
14 import static java.lang.Math.abs;//可以使用通配符
15 public class Demo {
16 public static void main(String[] args) {
17 //自动装箱和拆箱
18 Integer intObj = 20;//自动装箱
19 int num = intObj + 10;//自动拆箱
20 //泛型
21 ArrayList<String> strList = new ArrayList<>();
22 strList.add("aaa");
23 //增强for:可以遍历数组,Collection类型的集合(List和Set)
24 for(String s : strList){
25 System.out.println(s);
26 }
27
28 //静态导入:
29 System.out.println("-5的绝对值:" + abs(-5));
30
31 //可变参数
32 //调用可变参数的方法,可以不传递参数
33 System.out.println(sum());
34 System.out.println(sum(10,3,24,32,44,2,432,4,32,4325,24324,32,43,24,324,32,4));
35
36 }
37
38 //具有可变参数的方法
39 public static int sum(int...nums){
40 int sum = 0;
41 for(int i : nums){
42 sum+=i;
43 }
44 return sum;
45 }
46 }
13.自定义枚举
回顾:单例模式:在程序运行期间,某些类的只能有一个对象存在;
多例模式:在程序运行期间,有些类只允许有特定数量的对象。
例如:一张扑克是一个类;全局只需要:54个对象;
筛子:
枚举,就是基于多例模式的:
例如:我们程序需要使用到颜色,我们使用MyColor类定义颜色,但只需要用到三种颜色:红、绿、蓝,
所以运行时,只需要有三个MyColor对象即可;
1 public class Demo {
2 public static void main(String[] args) {
3 // MyColor c1 = new MyColor();//不能直接构造对象
4 MyColor c1 = MyColor.RED;
5 System.out.println(c1);
6 c1.show();
7
8 MyColor c2 = MyColor.BLUE;
9 System.out.println(c2);
10 c2.show();
11
12 MyColor c3 = MyColor.GREEN;
13 System.out.println(c3);
14 c3.show();
15
16 }
17 }
18
19 /*
20 * 多例模式的MyColor:
21 *
22 * 1.将构造方法私有化。
23 * 2.内部提供三个MyColor对象;作为成员变量
24 */
25
26 public abstract class MyColor {
27 public static MyColor RED = new MyColor("红"){//匿名的内部子类对象
28 @Override
29 public void show() {
30 System.out.println("红色的show()方法");
31 }
32 };
33 public static MyColor GREEN = new MyColor("绿"){
34 @Override
35 public void show() {
36 System.out.println("绿色的show()方法");
37 }
38
39 };
40 public static MyColor BLUE = new MyColor("蓝"){
41 @Override
42 public void show() {
43 System.out.println("蓝色的show()方法");
44 }
45
46 };
47 //增加其它成员变量
48 private String name;
49
50 //将构造
51 private MyColor(String name){
52 this.name = name;
53 }
54
55 public String toString(){
56 return "我是:" + name + " 色的。";
57 }
58 //添加一个抽象方法
59 public abstract void show();
60
61 }
14.通过enum实现枚举类
1 public class Demo {
2 public static void main(String[] args) {
3 MyColor c1 = MyColor.RED;
4 System.out.println(c1);
5 c1.show();
6
7 MyColor c2 = MyColor.GREEN;
8 System.out.println(c2);
9 c2.show();
10
11
12 }
13 }
14
15 public enum MyColor {
16 RED("红"){
17 public void show() {
18 System.out.println("我是红色的");
19 }
20 },GREEN("绿"){
21 public void show() {
22 System.out.println("我是绿色的");
23 }
24 },BLUE("蓝"){
25 public void show() {
26 System.out.println("我是蓝色的");
27 }
28 };
29 //可以定义自有的成员变量,但,一定要放在枚举项之后。也就是:保证枚举项在先;
30 private String name;
31
32 private MyColor(String name){
33 this.name = name;
34 }
35
36 public String toString(){
37 return this.name;
38 }
39 //可以定义抽象方法
40 public abstract void show();
41 }
42
43 public enum MyColor2 {
44 RED,GREEN,BLUE;
45 private String name;
46 }
15.enum类的常用方法
枚举类的常用方法:
int compareTo(E o):比较索引
String name():获取名称:
int ordinal():取出索引
String toString():
<T> T valueOf(Class<T> type,String name)
values() :没有在帮助文档中出现,但反编译后能看到此方法;
以数组的方式返回内部的所有枚举项;
1 public class Demo {
2 public static void main(String[] args) {
3 MyColor c1 = MyColor.RED;
4 MyColor c2 = MyColor.GREEN;
5 MyColor c3 = MyColor.BLUE;
6
7 System.out.println("c1.compareTo(c2) : " + c1.compareTo(c2));//比较是索引
8 System.out.println("c2.compareTo(c1) : " + c2.compareTo(c1));
9
10 System.out.println("c1.compareTo(c3) : " + c1.compareTo(c3));
11
12 System.out.println("c1.name() : " + c1.name());//变量(枚举项)的名字
13 System.out.println("c2.nane() : " + c2.name());
14
15 System.out.println("c1.ordinal() : " + c1.ordinal());
16 System.out.println("c2.ordinal() : " + c2.ordinal());
17 System.out.println("c3.ordinal() : " + c3.ordinal());
18
19 System.out.println(c1.toString());
20 System.out.println(c2.toString());
21 System.out.println(c3.toString());
22
23 //获取蓝色的枚举项
24 MyColor c4 = MyColor.valueOf(MyColor.class,"BLUE");
25 System.out.println("c4 = " + c4);
26
27 //遍历枚举
28 MyColor[] colorArray = MyColor.values();
29 for(MyColor c : colorArray){
30 System.out.println(c);
31 }
32
33
34 }
35 }
36
37 public enum MyColor {
38 RED("红"){
39 public void show() {
40 System.out.println("我是红色的");
41 }
42 },GREEN("绿"){
43 public void show() {
44 System.out.println("我是绿色的");
45 }
46 },BLUE("蓝"){
47 public void show() {
48 System.out.println("我是蓝色的");
49 }
50 };
51 //可以定义自有的成员变量,但,一定要放在枚举项之后。也就是:保证枚举项在先;
52 private String name;
53
54 private MyColor(String name){
55 this.name = name;
56 }
57
58 public String toString(){
59 return this.name;
60 }
61 //可以定义抽象方法
62 public abstract void show();
63 }
16.JDK7的新特性
二进制字面量:
数字字面量可以出现下划线
switch 语句可以用字符串
泛型简化
异常的多个catch合并
try-with-resources 语句
1 public class Demo {
2 public static void main(String[] args) {
3 //八进制
4 System.out.println(010);//8
5 //二进制:字面量
6 System.out.println(0b1010);
7 //2.数字字面量可以出现下划线
8 System.out.println(12_345_6_7_8.00);
9 //3.switch 语句可以用字符串
10 String s = "+";
11 switch(s){
12 case "+":
13 System.out.println("加法");
14 break;
15 case "-":
16 System.out.println("减法");
17 break;
18 case "*":
19 System.out.println("乘法");
20 break;
21 case "/":
22 System.out.println("除法");
23 break;
24 }
25 //4.泛型简化
26 ArrayList<String> list = new ArrayList<>();
27 //5.异常的多个catch合并
28 try{
29
30 }catch(NullPointerException | ArithmeticException e){
31
32 }
33
34 //6.try-with-resources 语句
35 //之前的try...catch形式;
36 /*FileInputStream in = null;
37 FileOutputStream out = null;
38 try {
39 in = new FileInputStream("aa.txt");
40 out = new FileOutputStream("bb.txt");
41 } catch (FileNotFoundException e) {
42 e.printStackTrace();
43 }finally{
44 if(in != null){
45 try {
46 in.close();
47 } catch (IOException e) {
48 e.printStackTrace();
49 }
50 }
51 if(out != null){
52 try {
53 out.close();
54 } catch (IOException e) {
55 e.printStackTrace();
56 }
57 }
58 }*/
59
60 //JDK7以后
61 try(
62 //在try中定义的变量,不需要我们手动关闭,用完后,虚拟机可以为我们关闭;所以,不需要finally语句;也不用关闭
63 FileInputStream in = new FileInputStream("aa.txt");
64 FileOutputStream out = new FileOutputStream("bb.txt");
65 ){
66
67 }catch(FileNotFoundException e){
68
69 } catch (IOException e) {
70 e.printStackTrace();
71 }
72
73
74 }
75 }
来源:https://www.cnblogs.com/linmusen/p/4709297.html