转义字符 \t 制表符 \n 换行符 \ \ 一个\ \ “ 一个” \ ‘ 一个’
八大基本数据类型 数值型:整数类型(byte,short,int,long)、浮点类型(float,double)
字符型:(char) char类型为2个字节,本质就是一个数值
布尔型:(boolean)
整数型 byte 1字节 -128~127
short 2字节
int 4字节
long 长整型 8字节
出现在代码中的整数,默认为int。声明long常量需后面加L或l
浮点型 float 4字节
double 8字节
出现在代码中的小数,默认为double。声明float常量需后面加F或f
字符型 char 2字节,可以用来存汉字,char的本质是一个整数,输出的是unicode码对应的字符。如果非要输出一个整数,需要强制转换(int)
布尔型 boolean 1字节
自动类型转换 数据类型按精度大小排序 char -> int -> long -> float -> double
byte -> short -> int -> long -> float -> double
注意事项 boolean不转换
char和short、char和byte之间不进行自动转换
byte、short、char计算时转换为int类型
命名规范 包名 全小写
类名 大驼峰
变量名、方法名 小驼峰
常量名 全大写,多个单词用下划线连接
自增运算 int y = 1 ;int c = y++;y = 1 ; temp = y; y = y+1 ; c = temp; int i = 1 ;i = i++; i = 1 ; temp = i; i = i + 1 ; i = temp;
关系运算符 A instance of B 表示A是否是B这个类的对象
逻辑与短路运算符 短路&& 断路|| 取反!
逻辑& 逻辑或|| 逻辑异或^
区别 & 不管真假两边都运算
&& 左边为假,右边就不运算
| 不管真假两边都运算
|| 左边为真右边就不运算
数组 一维数组 char [] chars1 = {'a' ,'b' ,'c' };char [] chars2[] = {'a' ,'b' ,'c' };char chars3[] = new char []{'a' ,'b' ,'c' };char [] chars4[] = new char []{'a' ,'b' ,'c' };char [] chars5 = new char [3 ];chars5[0 ] = 'a' ; chars5[1 ] = 'b' ; chars5[2 ] = 'c' ; char chars5[] = new char [3 ];chars5[0 ] = 'a' ; chars5[1 ] = 'b' ; chars5[2 ] = 'c' ; char chars6[]; chars6 = new char [3 ]; chars6[0 ] = 'a' ; chars6[1 ] = 'b' ; chars6[2 ] = 'c' ; char [] chars7 = new char [3 ];int length = chars7.length;
二维数组 int [][] arr = new int [2 ][3 ];a[0 ][0 ] = 100 ; int [][]arr2 = new int [2 ][];arr2[0 ] = new int [2 ]; arr2[1 ] = new int [3 ]; int [][] arr3 = { {1 ,2 ,3 }, {4 ,5 ,6 } }; int length1 = arr.length;int length2 = arr[0 ].length;int length2 = arr[1 ].length;int [][] arr3 = { {1 ,2 ,3 }, {4 ,5 } }; for (int i = 0 ;i<arr3.length;i++){ for (int j = 0 ;j<arr3[i].length;j++){ System.out.println(arr3[i][j]); } }
十进制转十六进制 public class Main { public static void main (String[] args) { int a = 31 ; StringBuilder stringBuilder = new StringBuilder (); char [] chars = {'0' ,'1' ,'2' ,'3' ,'4' ,'5' ,'6' ,'7' ,'8' ,'9' ,'A' ,'B' ,'C' ,'D' ,'E' ,'F' }; while (a>0 ){ int index = a%16 ; char temp = chars[index]; stringBuilder.append(temp); a/=16 ; } System.out.println(stringBuilder.reverse().toString()); } }
Java API中文文档 https://www.matools.com/
static 静态属性(类属性)与实例属性(对象属性) 静态属性,只有一份,可以通过 类名.属性名/对象,属性名 来赋值和访问; 实例属性,每个对象都有一份,只能通过对象.属性名 来赋值和访问
静态方法与实例方法(对象方法) 静态方法中只能调用静态方法,不能访问实例属性
实例方法中可以调用静态方法和实例方法,也可以访问静态属性和实例属性
可变参数 int sum(int… nums){}
可变参数,可以当作数组处理
可变参数的实参可以为0个或任意多个
可变参数的实参可以为数组
可变参数的本质就是数组
可变参数可以和普通类型的参数一起放在形参列表,但必须保证可变参数在最后一个形参列表中只能出现一个可变参数
@SuppressWarnings("all")
是一个 Java 注解,用于抑制编译器在代码中发现的所有警告信息。这个注解通常用于类、方法、字段或局部变量上,目的是阻止编译器显示警告,以便在代码中处理潜在问题时不受警告的干扰。
public class Main { public static void main (String[] args) throws Exception { System.out.println(sum(5 ,6 )); int [] a = new int [] {1 ,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,10 }; System.out.println(sum(a)); } static int sum (int ... a) { int result = 0 ; for (int i = 0 ;i<a.length;i++){ result += a[i]; } return result; } }
构造器 对象创建流程 class Person { int age = 90 ; String name; Person(String n,int a){ name = n; age = a; } } Person p = new Person ("xiaojianbang" ,31 );
加载Person类信息,只会加载一次
在堆中分配空间(地址)
完成对象初始化
默认初始化 age=0 name=null
显示初始化 age=90 name=null
构造器显示化 age=20 name=null
在对象在堆中的地址,返回给p(p是对象名,也可以理解成是对象的引用)
this(方法) this(实参列表)
用于构造方法之间的访问,必须是构造器中的第一个语句
public String name;public static int age;public Cat (String name) { this (name,30 ); this .name = name; System.out.println(this .name); System.out.println(this .hashCode()); } public Cat (String dnamem,int age) { Cat.age = age; System.out.println("Cat" ); }
访问修饰符
封装 public class Account { private String name = null ; private double balance = 0 ; private String password = null ; public Strng getPassword () { return password; } public void setPassword (String password) { if (password == null ){ System.out.println("密码设置不能为空" ); return ; } if (password.length() == 6 ){ this .password = password; }else { System.out.println("密码必须等于6位" ); } } public double getBalance () { return balance; } public void setBalance (double balance) { if (balance<=0 ){ System.out.println("余额必须大于20" ); }else { this .balance = balance; } } public String getName () { return name; } public void setName (String naem) { if (name == null ){ System.out.println("名字不能为空" ); return ; } if (this .name != null ){ System.out.println("名字只能修改一次" ); }else { if (name.length()<2 ||name.length()>4 ){ System.out.println("名字长度需要在2-4位" ); }else { this .name = name; } } } }
继承 Java是单继承机制,子类只能直接继承一个父类,所有类都是Object类的一个子类,Ctrl + h 可查看继承关系
Person.java package com.xiaojiangbang.java;public class Person { private String name = null ; private int age = 0 ; private boolean sex = false ; public String getName () { return name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public boolean isSex () { return sex; } public void setSex (boolean sex) { this .sex = sex; } }
Student.java package com.xiaojianbang.java;public class Student extends Person { private double shenghuofei = 0 ; public double getShenghuofei () { return shenghuofei; } public void setShenghuofei (double shenghuofei) { this .shenghuofei = shenghuofei } }
Teacher.java package com.xiaojianbang.java;public class Teacher extends Person { private String name = null ; private int age = 0 ; private boolean sex = false ; private double gongzi = 0 ; public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public boolean isSex () { return sex; } public void setSex (boolean sex) { this .sex = sex; } public double getGongzi () { return gongzi; } public void setGongzi (double gongzi) { this .gongzi = gongzi; } }
Main.java package com.xiaojianbang.java;public class Main (){ public static void main (String[] args) { Student student = new Student (); student.setName("xiaojianbang" ); student.setAge(20 ); student.setShenghuofei(100 ); System.out.println(student.getName()) } }
父类构造器 当创建子类对象时,不管使用子类的哪个构造器,默认情况下总会去调用父类的无参构造器super();
如果父类没有提供无参的构造器,则须在子类的构造器中用super去指定使用父类的哪个构造器super(参数列表)
父类构造器的调用不限于直接父类,一直往上追溯到Object类(顶级父类)
注意:super()和this都只能放在构造器第一行,因此这两个方法不能共存在一个构造器,子类的每一个构造方法,都需要先访问父类的构造方法 Main.java package com.xiaojiangbang.java;public class Main { public static void main (Stirng[] args) { Student student = new Student ("umr" ,30 ,true ,100 ); System.out.println(student.getName()); Teacher teacher = new Teacher ("xiaojianbang" ,30 ,true ,200 ); System.out.println(teacher.getName()); } }
Person.java package com.xiaojianbang.java;public class Person { private String name = null ; private int age = 0 ; private boolean sex = false ; public Person (String name, int age, boolean sex) { this .name = name; this .age = age; this .sex = sex; System.out.println("Person 有参构造" ); } public Person () { System.out.println("Person 无参构造" ); } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public boolean isSex () { return sex; } public void setSex (boolean sex) { this .sex = sex; } }
Teacher.java package com.xiaojianbang.java;public class Teacher extends Person { private String name = null ; private int age = 0 ; private boolean sex = false ; private double gongzi = 0 ; public Teacher () { System.out.println("Teacher 无参构造器" ); } public Teacher (String name, int age, boolean sex,double gongzi) { this .gongzi = gongzi; System.out.println("Teacher 有参构造器" ); } public String getName () { return name; } public void setName (String name) { this .name = name; } public int getAge () { return age; } public void setAge (int age) { this .age = age; } public boolean isSex () { return sex; } public void setSex (boolean sex) { this .sex = sex; } public double getGongzi () { return gongzi; } public void setGongzi (double gongzi) { this .gongzi = gongzi; } }
Student.java package com.xiaojianbang.java;public class Student extends Person { private double shenghuofei = 0 ; public Student (String name, int age, boolean sex,double shenghuofei) { this .shenghuofei = shenghuofei; System.out.println("Student 有参构造" ); } public Student () { System.out.println("Studnet 无参构造" ); } public double getShenghuofei () { return shenghuofei; } public void setShenghuofei (double shenghuofei) { this .shenghuofei = shenghuofei; } }
super super的作用
子类和父类具有同名属性和方法时,默认使用子类的同名属性和方法。为了访问父类的属性或方法,必须通过super来调用
super代表父类对象的引用,用于访问父类对象的属性、方法、构造器、
访问父类的属性(收访问修饰符影响)
访问父类的方法(受访问修饰符的影响)
访问父类的构造器
方法重写 方法重写的特点
方法重写也叫方法覆盖
子类方法的名称、参数,与父类完全相同
子类方法的返回类型和父类方法的返回类型一样,或者父类返回类型的子类,比如父类返回类型时Object,子类方法返回类型是String
子类方法不能缩小父类方法的访问权限,可以扩大
重载与重写的区别 重载:同一个类中,方法名相同,但参数类型、个数或顺序不同,与返回值无关,与修饰符无关
重写:父类和子类中,方法名相同,参数相同,子类返回类型与父类返回类型一样或者是其子类,子类不能缩小父类的访问范围
代码块 静态代码块 可以定义多个,与静态属性初始化优先级一样,按定义顺序执行
随着类加载而执行,只执行一次,执行时机比普通代码块早
普通代码块 可以定义多个,与实例属性初始化优先级一样,按定义顺序执行
随着对象创建而执行,提高构造器代码复用性,每次创建对象都会执行
先调用父类构造器,接着调用普通代码块,再调用本类构造器
创建对象时的调用顺序 1、父类的静态代码块和静态属性
2、子类的静态代码块和静态属性
3、父类的普通代码块和普通属性初始化
4、父类的构造方法
5、子类的普通代码块和普通属性初始化
6、子类的构造方法
静态代码块只能调用静态成员,普通代码块可以调用任意成员 多态 Person.java package com.xiaojianbang.java;public class Person { public String callPlay () { return "Person" ; } }
Teacher.java package com.xiaojianbang.java;public class Teacher extends Person { public String callPlay () { return "Teacher" ; } }
Person.java package com.xiaojianbang.java; public class Person { public String callPlay () { return "Person" ; } }
Main.java package com.xiaojianbang.java;public class Main { public static void main (String[] args) { Student student = new Student (); Teacher teacher = new Teacher (); Person person = new Person (); test(person); test(teacher); test(student); } public static void test (Person p) { System.out.println("test(Person p)" ); System.out.println(p.callPlay()); } public static void test (Student p) { System.out.println("test(Student p)" ); System.out.println(p.callPlay()); } public static void test (Teacher p) { System.out.println("test(Teacher p)" ); System.out.println(p.callPlay()); } }
多态参数 参数定义成父类类型,就可以传任意子类类型进去
package com.xiaojianbang.java;public class Main { public static void main (String[] args) { Student student = new Student (); Teacher teacher = new Teacher (); Person person = new Person (); test(person); test(teacher); test(student); } public static void test (Person p) { System.out.println("test(Person p)" ); System.out.println(p.callPlay()); } }
向上转型
语法:父类类型 引用名 = new 子类类型();
父类应用指向子类对象
编译类型看左边,运行类型看右边
可以调用父类中的所有成员(受访问修饰符影响)
调用的时候,子类有就用子类的成员,子类没有就找父类的成员(就近原则)
不能调用子类中的特有成员
public class Main { public static void main (String[] args) { Person person1 = new Student (); Person person2 = new Teacher (); Person person3 = new Person (); test(person1); test(person2); test(person3); } public static void test (Person p) { System.out.println("test(Person p)" ); System.out.println(p.callPlay()); } }
注意事项
多态的前提:两个对象(类)存在继承关系
属性的值看编译类型
只要编译能通过,方法都是看运行类型,属性看编译类型
instanceOf 比较操作符,用于判断对象的运行类型是否为xx类型或是xx类型的子类型
要调用子类中特有成员,还需要向下转型(其实就是强转),转回实际类型,瞎转会报错
多态数组 数组的定义类型位父类类型,里面保存的实际元素类型为子类类型
创建1个Person、Student、Teacher对象,都放到一个数组中,遍历该数组成员,调用callPlay方法遍历过程中调用Student、Teacher对象,都放到一个数组中,遍历该数组成员,调用callPlay方法
Person.java package com.xiaojianbang.java;public class Person { public String callPlay () { return "Person" ; } }
Student.java package com.xiaojianbang.java;public class Student extends Person { public String callPlay () { return "Student" ; } public void study () { System.out.println("study" ); } }
Teacher.java package com.xiaojianbang.java;public class Teacher extends Person { public String callPlay () { return "Teacher" ; } public void teach () { System.out.println("teach" ); } }
Main.java package com.xiaojianbang.java;public class Main { Person person1 = new Student (); Person person2 = new Teacher (); Person person3 = new Person (); Person[] p = new Person []{person1,person2,person3}; for (int i = 0 ;i<p.length;i++){ System.out.println(p[i].callPlay()); if (p[i] instanceof Student){ Student s = (Student) p[i]; s.study(); }else if (p[i] instanceof Teacher){ Teacher t = (Teacher) p[i]; t.teach(); }else if (p[i] instanceof Person){ } } }
动态绑定机制
当调用对象方法的时候,该方法会和该对象的内存地址/运行类型绑定
当调用对象属性时,没有动态绑定机制,以就近原则为准
equals
== 既可以判断基本类型,也可以判断引用类型,基本类型判断值,应用类型判断地址
equals是Object类中的方法,只能判断引用类型,默认判断的是地址是否相等,子类一般会重写equals方法,用于判断内容是否相等,比如Integer、String
package com.xiaojianbang.java;public class Main { public static void main (String[] args) { int a = 100 ; int b = 100 ; System.out.println(a==b); Student student = new Student (); Student student1 = new Student (); System.out.println(student==student1); String aa = "xiaojianbang" ; System.out.println(aa.equals("xiaojianbang" )); Integer aaa = 100 ; Integer bbb = 100 ; System.out.println(aaa.equals(bbb)); } }
注意:字符串都放在字符串常量池中 p1.name="xiaojiangbang" ; p2.name="xiaojiangbang" ; p1.name==p2.name;为真
toString public String tostring () { return getClass().getName()+"@" +Integer.toHexString(hashCode()); }
默认返回:全类名+@+哈希值的十六进制
子类往往重写toString方法,用于返回对象的属性信息
当直接输出一个对象时,toString方法会被默认的调用
finalize
子类可以重写该方法,做一些释放资源的操作
某个对象没有任何引用时,垃圾回收机制就会销毁该对象,销毁前先调用finalize方法
垃圾回收机制什么时候调用,由系统来决定
也可以通过System.gc()主动触发垃圾回收机制,但不一定是立马回收
final final应用场景
不希望类被继承
不希望类的属性值被修改(常量)
不希望父类的方法被子类覆盖/重写(override)
不希望局部变量(参数)被修改(局部常量)
final修饰实例属性,可以在定义时、构造器中、普通代码块中赋初值 final修饰静态属性,可以在定义时、静态代码块中赋初值 final注意事项
final修饰属性,必须赋值,并且不能再次修改
final可以修饰类、属性、方法和局部变量(参数),不能修饰构造器
包装类(Integer、Double、Float、Boolean)和String都是final类
final修饰类,不能被继承,但是可以实例化对象
final和static搭配使用,不会加载类
抽象类
abstract只能修饰类和方法
用abstract关键字来修饰一个类时,这个类就叫抽象类
用abstract关键字来修饰一个方法时,这个方法就是抽象方法
注意事项
抽象类可以有任意成员,可以被继承,可以没有抽象方法
抽象类不能被实例化
有了抽象方法,则这个类必须声明为abstract
继承了抽象类,则必须实现抽象类的所有抽象方法,除非它们自己也声明为abstract类
抽象方法是不能用private、final、static来修饰
C.java public abstract class C { public abstract void job () ; public void calc () { System.out.println("开始计算..." ); job(); System.out.println("计算结束..." ); } }
A.java public class A extends C { public void job () { int result = 0 ; for (int i = 0 ; i <= 100 ; i++){ result+=i; } System.out.println(result); } }
B.java public class B extends C { public void job () { int result = 0 ; for (int i = 0 ; i<= 100 ; i++){ if (i%2 == 0 ){ result += i; } } System.out.println(result); } }
接口 基本语法 interface 接口名{ } class 类名 implements 接口名{ 必须实现接口的所有抽象方法 }
jdk7.0前接口里的所有方法都是抽象方法,jdk8.0后接口可以有静态方法(static)、默认方法(default),可以有具体实现
USB接口 package com.xiaojianbang.java;public interface USB { public void start () ; public void stop () ; public default void moren () { System.out.println("USB接口的默认方法" ); } public static void jingtai () { System.out.println("USB接口的静态方法" ); } }
Mouse.java package com.xiaojianbang.java;public class Mouse implements USB { @Override public void start () { System.out.println("鼠标开始工作" ); } @Override public void stop () { System.out.println("键盘停止工作" ); } }
Keyboard.java package com.xiaojianbang.java;public class Keyboard implements USB { @Override public void start () { System.out.println("键盘开始工作了" ); } @Override public void stop () { System.out.println("键盘结束工作了" ); } }
Main.java package com.xiaojianbang.java;public class Main { public static void main (String[] args) { Computer.work(new Mouse ()); Computer.work(new Keyboard ()); } public static void work (USB usb) { usb.start(); usb.stop(); } } class Computer { public static void work (USB usb) { usb.start(); usb.stop(); usb.moren(); USB.jingtai(); } }
接口注意事项
接口不能被实例化
接口的修饰符只能是public和默认,这点和类的修饰符是一样的
一个接口不能继承其它的类,但是可以继承多个别的接口,用” ,” 隔开
接口中的方法都是public方法,抽象方法可以不用abstract修饰
一个普通类实现接口,就必须将接口的所有方法都实现
抽象类实现接口,可以不用实现接口的方法
一个类同时可以实现多个接口
接口中的属性都是public static final 修饰符int a = 1;实际上是public static final int a = 1;(必须初始化)接口中属性的访问形式:接口名.属性名
接口的多态传递 interface B {}interface A extends B {}class C implements A {}B b = new C ();A a = new C ();
IDEA快捷键
成员内部类
package com.xiaojianbang.java;public class Main { public class void main(String[] args){ OuterClass outerclass = new OuterClass ("xiaojianbang" ,30 ); OuterClass.InnerClass innerClass = outerClass.test(); System.out.println(innerClass.getClass().getName()); OuterClass outClass = new OuterClass ("xiaojianbang" ,30 ); OuterClass.InnerClass innerClass = outerClass.new InnerClass ("PHP" ); System.out.pringln(innerClass.getClass.getName()); System.out.println(innerClass.language); innerClass.abc(); System.out.println(outerClass.getClass()); System.out.println(outerClass.getClass().getName()); } } class OuterClass { public String name = "xiaojianbang" ; private int age = 0 ; public boolean sex = false ; public InnerClass test () { InnerClass innnerClass = new InnerClass ("python" ); System.out.println(innerClass.language); return innerClass; } static { System.out.println("OuterClass static block" ); } public OuterClass (String name, int age) { this .name = name; this .age = age; } class InnerClass { public String language = "Java" ; public String name = "umr" ; public void abc () { System.out.println(OuterClass.this .name); System.out.println(name); System.out.println(sex); } { System.out.println("InnerClass block" ); } public InnerClass (String language) { this .language = language; } } }
静态内部类
静态内部类不能访问外部类的非静态成员,非静态方法可以调用静态方法和非静态方法,静态方法只能调用静态方法
public class Main { public static void main (String[] args) { OuterClass.InnerClass innerClass = OuterClass.getInnerClass(); System.out.println(innerClass.language); OuterClass.InnerClass php = new OuterClass .InnerClass("PHP" ); System.out.println(OuterClass.sex); } } class OuterClass { public String name = "xiaojianbang" ; private int age = 0 ; public static boolean sex = false ; public InnerClass test () { InnerClass innerClass = new InnerClass ("python" ); System.out.println(innerClass.language); return innerClass; } static { System.out.println("OuterClass static block" ); } public OuterClass (String name, int age) { this .name = name; this .age = age; } public static InnerClass getInnerClass () { public String language = "Java" ; public String name = "umr" ; public void abc () { System.out.println(name); } { System.out.println("InnerClass block" ); } public InnerClass (String language) { this .language = language; } } }
局部内部类
局部内部类不能定义静态成员
package com.xiaojiangbang.java;public class Main { OuterClass xiaojianbang = new OuterClass ("xiaojianbang" ,30 ); xiaojianbang.getInnerClass(); xiaojianbang.getInnerClass1(); } class OuterClass { public String name = "xiaojianbang" ; private int age = 0 ; public static boolean sex = false ; static { System.out.println("OuterClass static block" ); } public OuterClass (String name, int age) { this .name = name; this .age = age; } public void getInnerClass () { final class InnerClass { public String language = "Java" ; public String name = "umr" ; public String sex = "abc" ; public void abc () { System.out.println(name); System.out.println(sex); System.out.println(OuterClass.this .name); System.out.println(OuterCLass.sex); } { System.out.println("InnerClass block" ); } public InnerClass (String language) { this .language = language; } } InnerClass php = new InnerClass ("PHP" ); php.abc(); System.out.prinln(php.getClass().getName()); } }
匿名内部类
内部匿名类不能定义静态成员,只有当匿名类别类处于外部类里面的时候,才能使用外部类.this.xxx访问外部类的示例成员
接口USB.java package com.xiaojianbang.java;public interface USB { public abstract void start () ; public abstract void stop () ; }
抽象类USB2.java package com.xiaojianbang.java;public abstract class USB2 { public static String name = "xiaojianbang" ; public abstract void start () ; public abstract void stop () ; }
Main.java package com.xiaojianbang.java;public class Main { public static void main (String[] args) { Computer computer = new Computer (); computer.work(new USB (){ @Override public void start () { System.out.println("键盘开始工作了" ); } @Override public void stop () { System.out.println("键盘停止工作了" ); } }); computer.work(new USB (){ @Override public void start () { System.out.println("鼠标开始工作了" ); } @Override public void stop () { System.out.println("鼠标结束工作" ); } }); USB2 usb2 = new USB2 (){ public String name = "umr" ; @Override public void start () { System.out.println(name); System.out.println(USB2.name); System.out.println("基于抽象类的匿名内部类start" ); } @Override public void stop () { System.out.println("基于抽象类的匿名内部类stop" ); } }; usb2.start(); usb2.stop(); System.out.println(usb2.getClass().getName()); System.out.println(new USB2 (){ @Override public void start () { System.out.println("基于抽象类的匿名内部类start2" ); } @Override public void stop () { System.out.println("基于抽象类的匿名内部了stop2" ); } }).getClass().getName()); } } class Computer { public static void work (USB usb) { ubs.start(); usb.stop(); } }
枚举类
自定义枚举类 package com.xiaojianbang.java;import java.nio.charset.StandardCharsets;public class Main (){ @SuppressWarnings({"all"}) ; public static void main (String[] args) { System.out.println(StandardCharset.UTF_8); System.out.println(Season.SPRING); } } class Season { public String name = null ; public String desc = null ; public static final String SPRING1 = "春天" ; public static final Season SPRING = new Season ("春天" ,"暖和" ); public static final Season SUMMER = new Season ("夏天" ,"很热" ); public static final Season AUTUMN = new Season ("秋天" ,"凉爽" ); public static final Season WINTER = new Season ("冬天" ,"很冷" ); @Override public String toString () { return "Season{" + "name=" + '\'' + name + '\'' + ", desc=" + '\'' + desc + '\'' + '}' ; } }
系统提供的枚举类(枚举对象必须放在枚举类的第一行) public class Main { @SuppressWarnings({"all"}) ; public static void main (String[] args) { System.out.println(Season.SPRING); } } enum Season { xxxx,SPRING("春天" ,"暖和" ),SUMMER("夏天" ,"很热" ),AUTUMN("秋天" ,"凉爽" ),WINTER("冬天" ,"很冷" ); public String name = null ; public String desc = null ; private Season () { } private Season (String name, String desc) { this .name = name; this .desc = desc; } @Override public String toString () { return "Season{" + "name=" + '\'' + name + '\'' + ", desc=" + '\'' + desc + '\'' + '}' ; } }
enum相关方法
使用Javap反编译Season.class
package com.xiaojianbang.java;import java.nio.charset.StandardCharsets;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Season autumn = Season.AUTUMN; System.out.println(autumn); System.out.println(autumn.name()); System.out.println(autumn.ordinal()); Season[] seasons = Season.values(); Season autumn1 = Season.valueOf("AUTUMN" ); System.out.println(Season.SUMMER.compareTo(Season.AUTUMN)); } } enum Season { SPRING("春天" ,"暖和" ),SUMMER("夏天" ,"很热" ),AUTUMN("秋天" ,"凉爽" ),WINTER("冬天" ,"很冷" ); public String name = null ; public String desc = null ; private Season () { } private Season (String name,String desc) { this .name = name; this .desc = desc; } @Override public String toString () { return "Season{" + "name=" + '\'' + name + '\'' + ", desc=" + '\'' + desc + '\'' + '}' ; } }
注解
异常
包装类
字符串
package com.xiaojianbang.java;import java.nio.charset.StandardCharsets;import java.util.Arrays;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { String a = "xiaojianbang" ; String b = new String ("xiaojianbang" ); char [] chars = a.toCharArray(); String s = Arrays.toString(chars); System.out.println(s); } }
字符串编码
package com.xiaojianbang.java;import com.sun.org.apache.xerces.internal.impl.dv.util.HexBin;import java.nio.charset.StandardCharsets;import java.util.Arrays;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { String name = "小肩膀8888" ; String s = new String (name.getBytes(StandardCharsets.UTF_8),StandardCharsets.ISO_8859_1); System.out.println(s); byte [] bytes = name.getBytes(StandardCharsets.UTF_8); String s1 = Arrays.toString(bytes); System.out.println(s1); System.out.println(bytes.length); byte [] ISO_bytes = name.getBytes(StandardCharsets.ISO_8859_1); String ISO_s1 = Arrays.toString(ISO_bytes); System.out.println(ISO_s1); System.out.println(ISO_bytes.length); String name = "小肩膀8888" ; char [] chars = name.toCharArray(); String s = Arrays.toString(chars); System.out.println(s); String name = "小肩膀8888" ; String ISO_s = new String (name.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1); System.out.println(ISO_s); String UTF8_s= new String (ISO_s.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8); System.out.println(UTF8_s); byte [] str_iso_bytes = ISO_s.getBytes(StandardCharsets.ISO_8859_1); byte [] str_utf8_bytes = UTF8_s.getBytes(StandardCharsets.UTF_8); System.out.println(Arrays.toString(str_iso_bytes)); System.out.println(Arrays.toString(str_utf8_bytes)); String HexEncodeStr = HexBin.encode(str_utf8_bytes); System.out.println(HexEncodeStr); byte [] decode = HexBin.decode(HexEncodeStr); System.out.println(Arrays.toString(decode)); } }
StringBuffer
Arrays
package com.xiaojianbang.java;import java.util.Arrays;import java.util.Comparator;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Integer[] aa = new Integer []{1 ,2000 ,3 ,4 ,5 ,6 ,7 ,8 ,99 ,95 ,65 ,33 ,65 ,200 ,900 }; System.out.println(Arrays.toString(aa)); Arrays.sort(aa); System.out.println(Arrays.toString(aa)); Arrays.sort(aa ,new Comparator () { @Override public int compare (Object o1, Object o2) { return (int )o1 -(int )o2; } }); } }
BigInteger
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.Arrays;import java.util.Comparator;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { BigInteger bigInteger1 = new BigInteger ("1234567895243532452345341242341234213" ); BigInteger bigInteger2 = new BigInteger ("123" ); BigInteger add = bigInteger1.add(bigInteger2); System.out.println(add); BigInteger sub = bigInteger1.subtract(bigInteger2); System.out.println(sub); BigInteger mul = bigInteger1.multiply(bigInteger2); System.out.println(mul); BigInteger div = bigInteger1.divide(bigInteger2); System.out.println(div); } }
集合
Collection
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Collection collection = new ArrayList (); collection.add(100 ); collection.add("xiaojianbang" ); collection.add(false ); collection.add(null ); collection.remove(null ); System.out.println(collection); collection.remove(1 ); System.out.println(collection); System.out.println(collection.contains(null )); System.out.println(collection.size()); System.out.println(collection.isEmpty()); collection.clear(); Collection collection2 = new ArrayList (); collection2.add("xiaojianbang1" ); collection2.add("xiaojianbang2" ); collection2.add("xiaojianbang3" ); collection.addAll(collection2); System.out.println(collection); System.out.println(collection.containsAll(collection2)); } }
List
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { List list = new ArrayList (); list.add("xiaojianbang" ); list.add("umr" ); list.add("rw" ); list.add(2 ,"java" ); System.out.println(list); List list2 = new ArrayList (); list2.add("xiaojianbang2" ); list2.add("umr2" ); list2.add("rw2" ); list2.add(2 ,"umr2" ); list2.addAll(0 ,list); System.out.println(list2); System.out.println(list.get(2 )); System.out.println(list2.indexOf("umr" )); System.out.println(list2.lastIndexOf("umr2" )); list.remove("umr2" ); list2.set(1 ,"umr" ); list2.subList(1 ,3 ); } }
List的遍历
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { List list = new ArrayList (); list.add("xiaojianbang" ); list.add("umr" ); list.add("rw" ); Iterator iterator = list.iterator(); Object next = iterator.next(); System.out.println(next); Object next2 = iterator.next(); System.out.println(next2); while (iterator.hasNext()) { Object nexted = iterator.next(); System.out.println(nexted); } for (Object o : list) { System.out.println(o); } for (int i = 0 ; i<list.size(); i++) { System.out.println(list.get(i)); } } }
ArrayList
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { ArrayList arrayList = new ArrayList (); arrayList.add("1" ); for (int i = 1 ;i<11 ;i++){ arrayList.add(i); } System.out.println(arrayList); } }
Vector
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Vector vector = new Vector (3 ,5 ); for (int i = 0 ;i<11 ;i++){ vector.add(i); } System.out.println(vector); } }
LinkedList
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Node xiaojianbang = new Node ("xiaojianbang" ); Node rw = new Node ("rw" ); Node umr = new Node ("umr" ); xiaojianbang.next = rw; rw.next = umr; umr.prev = rw; rw.prev = xiaojianbang; Node first = xiaojianbang; Node last = umr; Node temp = first; while (temp != null ) { System.out.println(temp); temp = temp.next; } System.out.println("===========" ); temp = last; while (temp != null ) { System.out.println(temp); temp = temp.prev; } System.out.println("===========" ); Node java = new Node ("java" ); java.prev = rw; java.next = umr; umr.prev = java; rw.next = java; temp = first; while (temp != null ) { System.out.println(temp); temp = temp.next; } System.out.println("===========" ); temp = last; while (temp != null ) { System.out.println(temp); temp = temp.prev; } } } class Node { public Node prev; public Node next; public Object item; public Node (Object item) { this .item = item; } @Override public String toString () { return "Node{" + "item=" + item + '}' ; } }
LinkedList
HashSet
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { HashSet hashSet = new HashSet (); hashSet.add(1 ); hashSet.add(2 ); hashSet.add(3 ); hashSet.add(4 ); hashSet.add(5 ); hashSet.add(6 ); hashSet.add("xiaojianbang" ); hashSet.add("umr" ); hashSet.add("xiao" ); hashSet.add("xiaoxiao" ); for (int i = 0 ; i < 10 ; i++){ System.out.println(hashSet); } Iterator iterator = hashSet.iterator(); while (iterator.hasNext()) { Object next = iterator.next(); System.out.println(next); } System.out.println(hashSet); for (Object o : hashSet){ System.out.println(o); } } }
数组链表
package com.xiaojianbang.java;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Node[] nodes = new Node [16 ]; Node xiaojianbang = new Node ("xiaojianbang" ); nodes[2 ] = xiaojianbang; Node umr = new Node ("umr" ); xiaojianbang.next = umr; Node rw = new Node ("rw" ); umr.next = rw; System.out.println(nodes); } } class Node { public Object item; public Node next; public Node (Object tiem) { this .item = tiem; } @Override public String toString () { return "Node{" +"item" + item + '}' ; } }
HashSet练习题
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { HashSet hashSet = new HashSet (); hashSet.add(new A ("xiaojianbang" ,31 )); hashSet.add(new A ("xiaojianbang" ,31 )); hashSet.add(new A ("rw" ,30 )); hashSet.add(new A ("rw" ,30 )); hashSet.add(new A ("umr" ,29 )); hashSet.add(new A ("umr" ,29 )); System.out.println(hashSet); } } class A { public String name; public int age = 0 ; public A (String name, int age) { this .name = name; this .age = age; } @Override public boolean equals (Object o) { if (this == o) return true ; if (o == null || getClass() != o.getClass()) return false ; A a = (A) o; return age == a.age && Objects.equals(name, a.name); } @Override public int hashCode () { return Objects.hash(name, age); } @Override public String toString () { return "A{" + "name='" + name + '\'' + ", age=" + age + '}' ; } }
LinkedHashSet
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { HashSet hashSet = new LinkedHashSet () ; hashSet.add("xiaojianbang" ); hashSet.add("xiaojianban" ); hashSet.add("xiaojian" ); hashSet.add("xiaojia" ); System.out.println(hashSet); } }
Map接口特点
Map接口常用方法
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Map hashMap = new HashMap (); hashMap.put("user" ,"xiaojianbang" ); hashMap.put("pass" ,"a12345678" ); hashMap.put("code" ,123456 ); Integer integer = new Integer (100 ); hashMap.put(integer,null ); hashMap.remove("code" ); hashMap.get("pass" ); System.out.println(hashMap.get("pass" )); System.out.println(hashMap.size()); System.out.println(hashMap.isEmpty()); hashMap.clear(); System.out.println(hashMap); } }
HaspMap的遍历
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { HashMap hashMap = new HashMap (); hashMap.put("user" ,"xiaojianbang" ); hashMap.put("pass" ,"a12345678" ); hashMap.put("code" ,123456 ); Integer integer = new Integer (100 ); hashMap.put(integer,null ); Set set = hashMap.keySet(); System.out.println(set.getClass()); set.forEach(new Consumer () { @Override public void accept (Object key) { System.out.println(key + "-" + hashMap.get(key)); } }); System.out.println("000000000000000000000000000000000000000" ); for (Object key : set) { System.out.println(key + "-" + hashMap.get(key)); } System.out.println("===================================" ); Iterator iterator1 = set.iterator(); while (iterator1.hasNext()) { Object key = iterator1.next(); System.out.println(key + "-" + hashMap.get(key)); } System.out.println("===================================" ); Collection values = hashMap.values(); for (Object value : values) { System.out.println(value); } System.out.println("===================================" ); Iterator iterator2 = values.iterator(); while (iterator2.hasNext()) { Object value = iterator2.next(); System.out.println(value); } System.out.println("===================================" ); Set set1 = hashMap.entrySet(); for (Object o : set1){ Map.Entry entry = (Map.Entry) o; System.out.println(entry.getKey() + "-" + entry.getValue()); } } }
HashTable
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Hashtable hashtable = new Hashtable (); hashtable.put("user" ,"xiaojianbang" ); hashtable.put("pass" ,"a12345678" ); hashtable.put("code" ,123456 ); Integer integer = new Integer (100 ); hashtable.put(integer,2 ); System.out.println(hashtable); } }
Properties
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { Properties prop = new Properties (); prop.put("user" ,"xiaojianbang" ); prop.put("pass" ,"a12345678" ); prop.put("code" ,123456 ); Integer integer = new Integer (100 ); prop.put(integer,2 ); System.out.println(prop); } }
TreeSet
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { TreeSet treeSet = new TreeSet (new Comparator () { @Override public int compare (Object o1, Object o2) { return (((String)o1).length()-((String)o2).length()); } }); treeSet.add("xiaojianbang" ); treeSet.add("xxxxxx" ); treeSet.add("rw" ); treeSet.add("rbe" ); treeSet.add("uad" ); treeSet.add("umr" ); System.out.println(treeSet); } }
TreeMap
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { TreeMap treeMap = new TreeMap (new Comparator () { @Override public int compare (Object o1, Object o2) { return (((String)o1).length()-((String)o2).length()); } }); treeMap.put("xiaojianbang" ,"1" ); treeMap.put("xxxxxx" ,"1" ); treeMap.put("rw" ,"1" ); treeMap.put("rbe" ,"1" ); treeMap.put("uad" ,"1" ); treeMap.put("umr" ,"1" ); treeMap.put("xiaojianbang" ,null ); System.out.println(treeMap); } }
Collections工具类
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { ArrayList arrayList = new ArrayList (9 ); arrayList.add(100 ); arrayList.add(200 ); arrayList.add(300 ); arrayList.add(400 ); arrayList.add(500 ); arrayList.add(600 ); arrayList.add(700 ); arrayList.add(800 ); arrayList.add(900 ); System.out.println(arrayList); System.out.println("==========================" ); Collections.reverse(arrayList); System.out.println(arrayList); System.out.println("==========================" ); for (int i = 0 ; i < 5 ; i++){ Collections.shuffle(arrayList); System.out.println(arrayList); } System.out.println("==========================" ); Collections.sort(arrayList); System.out.println(arrayList); System.out.println("==========================" ); Collections.sort(arrayList, new Comparator <Object>() { @Override public int compare (Object o1, Object o2) { return (Integer)o1 - ((Integer)o2); } }); System.out.println(arrayList); System.out.println("=========================" ); Collections.swap(arrayList, 0 , 1 ); System.out.println(arrayList); System.out.println("=========================" ); Object max = Collections.max(arrayList); System.out.println(max); System.out.println("=========================" ); Object max2 = Collections.max(arrayList,new Comparator () { @Override public int compare (Object o1, Object o2) { return (int )o2 - ((int )o1); } }); System.out.println(max); System.out.println("=========================" ); int frequency = Collections.frequency(arrayList,900 ); System.out.println(frequency); System.out.println("=========================" ); ArrayList new_arrayList = new ArrayList (arrayList.size()); for (int i = 0 ; i < arrayList.size(); i++){ new_arrayList.add(0 ); } Collections.copy(new_arrayList, arrayList); System.out.println(new_arrayList); System.out.println("=========================" ); Collections.replaceAll(new_arrayList, 1000 ,200 ); System.out.println(new BigInteger ("100" )); } }
集合使用的选择
泛型
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { ArrayList<Integer> arrayList = new ArrayList <Integer>( ); arrayList.add(1334 ); arrayList.add(100 ); arrayList.add(200 ); arrayList.add(300 ); arrayList.add(400 ); arrayList.add(500 ); arrayList.add(600 ); arrayList.add(700 ); arrayList.add(800 ); arrayList.add(900 ); System.out.println(arrayList); System.out.println("==========================" ); Collections.sort(arrayList, new Comparator <Integer>() { @Override public int compare (Integer o1, Integer o2) { return o1 -o2; } }); System.out.println(arrayList); System.out.println("=========================" ); People<String> stringPeople = new People <String>( ); System.out.println(stringPeople.test("xiaojianbang" )); HashMap<String, String> hashMap = new HashMap <>( ); hashMap.put("user1" , "xiaojianbang1" ); hashMap.put("user2" , "xiaojianbang2" ); hashMap.put("user3" , "xiaojianbang3" ); Set<Map.Entry<String, String>> set = hashMap.entrySet( ); Iterator<Map.Entry<String, String>> iterator = set.iterator( ); while (iterator.hasNext()) { Map.Entry<String, String> next = iterator.next(); System.out.println(next.getKey() + " " + next.getValue( )); } } } class People <X>{ public X name; public X test (X a) { return a; } }
自定义泛型类
package com.xiaojianbang.java;public class Main { @SuppressWarnings("{all}") public static void main (String[] args) { People<String,Integer,Boolean> people = new People <>(); System.out.println("xiaojianbang" ); people.names = new String []{"xxxx" ,"yyyy" }; } } class People <X,R,W>{ public X name; public R age; public W sex; public X[] names; public X test (X a) { return a; } }
自定义泛型接口
package com.xiaojianbang.java;import java.io.IOException;import java.math.BigInteger;import java.util.*;import java.util.function.Consumer;public class Main { @SuppressWarnings({"all"}) public static void main (String[] args) { People<String,Integer,Boolean> people = new People <>(); System.out.println("xiaojianbang" ); people.names = new String []{"xxxx" ,"yyyy" }; } } class People <X,R,W> implements IUSB <String,Integer,Boolean>{ public X name; public R age; public W sex; public X[] names; public X test (X a) { return a; } @Override public String test1 (String a, Integer b, Boolean c) { return "" ; } @Override public String test2 (String a, Integer b, Boolean c) { return IUSB.super .test2(a, b, c); } } interface IUSB <X,R,W>{ X test1 (X a,R b,W c) ; default X test2 (X a,R b,W c) { return a; } }
自定义泛型方法
public <T,S> T test (T a, S b) { return a; } public X test (X a,R b) { return a; }
泛型方法可以是静态,但是如果用了类声明的方法,就不能静态了
泛型通配符
package com.xiaojianbang.java;import java.util.*;public class Main (){ @SuppressWarnings({"all"}) public static void main (String[] args) throwsClassNotFoundException{ test1(new ArrayList <String>()); test1(new ArrayList <Integer>()); Class<?> aClass = Class.forName("java.lang.String" ); test2(new ArrayList <A>()); test2(new ArrayList <B>()); test2(new ArrayList <C>()); test3(new ArrayList <A>()); test3(new ArrayLIst <Object>()); test3(new ArrayList <>()); } public static List<?> test1(List<?> a){ return a; } public static List<?> test2(List<? extends A > a){ return a; } publci static List<?> test3(List<? super A> a){ return a; } } class A { } class B extends A { } class C extends B { }
Properties读配置文件 String filePath = new File ("" ).getCanonicalPath();
新建一个demo.properties class = Xiaojianbang method = printInfo
Hello.java import java.io.File;import java.io.FileInputStream;import java.Util.Porperties;import java.util.Porperties;public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception{ String filePath = new Flie ("" ).getCanoncalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStrem (filePath)); String class Name = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); } }
反射
public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception{ String filePath = new File ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Method method = cls.getMEthod(methodName); method.invoke(null ); } } class Xiaojianbang { pubilc static void printInfo () { System.out.println("qq: 23346534" ); } public static void printInfo2 () { System.out.println("VX: 1234534" ); } }
Class的获取
import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.lang.reflect.Method;import java.util.Properties;public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception { String filePath = new File ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Class<?> cls1 = Xiaojianbang.class; Class<?> cls2 = new Xiaojianbang ().getClass(); Class<?> cls3 = Xiaojianbang.class.getClassLoader().loadClass(className); Class<?> cls4 = new Xiaojianbang ().getClass().getClassLoader().loadClass(className); System.out.println(cls1); System.out.println(cls2); System.out.println(cls3); System.out.println(cls4); System.out.println(int .class); System.out.println(Integer.TYPE); System.out.println(Integer.class); Method method = cls.getMethod(methodName); method.invoke(null ); } } class Xiaojianbang { public static void printInfo () { System.out.println("qq: 23458757" ); } public static void printInfo2 () { System.out.println("VX: 12345678" ); } }
哪些有Class对象
public class Hello { @SuppressWarings({"all"}) public static void main (String[] args) throws Exception{ String filePath = new FIle ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); propertie.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Class<?> cls1 = Xiaojianbang.class; Class<?> cls2 = new Xiaoijanbang ().getClass(); Class<?> cls3 = Xiaojianbang.class.getClassLoader().loadClass(className); Class<?> cls4 = new Xiaojianbang ().getClass().getClassLoader().loadClass(className); System.out.println(cls1); System.out.println(cls2); System.out.println(cls3); System.out.println(cls4); System.out.println(int .class); System.out.println(Integer.TYPE); System.out.println(Integer.class); Method method = cls.getMethod(methodName); method.invoke(null ); new DemoI (){ @Override public void printInfo1 () { System.out.println("lelele" ); } }.printInfo1(); System.out.println("================================" ); System.out.println(Class.forName("Xiaojianbang" )); System.out.println(Class.forName("Xiaojianbang$Demo" )); System.out.println("Hello$1" ); System.out.println(DemoI.class); System.out.println(Thread.State.class); System.out.println(SuppressWarnings.class); System.out.println(int .class); System.out.println(Integer.class); System.out.println(void .class); String[] str1 = new String []{"xiaojianbang" }; String[][] str2 = new String [][]{{"xiaojianbang" }}; System.out.println(str1.getClass().getName()); System.out.println(String[].class); System.out.println(String[][].class); } } class Xiaojianbang { public static void printInfo () { System.out.println("qq: 23458757" ); } public static void printInfo2 () { System.out.println("VX: 12345678" ); } class Demo { } }
反射创建对象
import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.Method;import java.util.Properties;public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception { String filePath = new File ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Class<?> cls1 = Xiaojianbang.class; Class<?> cls2 = new Xiaojianbang ().getClass(); Class<?> cls3 = Xiaojianbang.class.getClassLoader().loadClass(className); Class<?> cls4 = new Xiaojianbang ().getClass().getClassLoader().loadClass(className); System.out.println(cls1); System.out.println(cls2); System.out.println(cls3); System.out.println(cls4); System.out.println(int .class); System.out.println(Integer.TYPE); System.out.println(Integer.class); Method method = cls.getMethod(methodName); method.invoke(null ); new DemoI (){ @Override public void printInfo1 () { System.out.println("lelele" ); } }.printInfo1(); System.out.println("================================" ); System.out.println(Class.forName("Xiaojianbang" )); System.out.println(Class.forName("Xiaojianbang$Demo" )); System.out.println("Hello$1" ); System.out.println(DemoI.class); System.out.println(Thread.State.class); System.out.println(SuppressWarnings.class); System.out.println(int .class); System.out.println(Integer.class); System.out.println(void .class); String[] str1 = new String []{"xiaojianbang" }; String[][] str2 = new String [][]{{"xiaojianbang" }}; System.out.println(str1.getClass().getName()); System.out.println(String[].class); System.out.println(String[][].class); System.out.println("================================" ); Class<?> xiaojianbang = Class.forName("Xiaojianbang" ); Object o1 = xiaojianbang.newInstance(); System.out.println(o1); Constructor<?> constructor = xiaojianbang.getConstructor(String.class,int .class); Object o2 = constructor.newInstance("xiaojianbang" , 30 ); System.out.println(o2); Constructor<?> constructor1 = xiaojianbang.getDeclaredConstructor(String.class); constructor1.setAccessible(true ); Object o3 = constructor1.newInstance("xiaojianbang" ); System.out.println(o3); } } class Xiaojianbang { public String name; public int age; public Xiaojianbang () { } public Xiaojianbang (String name, int age) { this .name = name; this .age = age; } private Xiaojianbang (String name) { this .name = name; } public static void printInfo () { System.out.println("qq: 23458757" ); } public static void printInfo2 () { System.out.println("VX: 12345678" ); } class Demo { } @Override public String toString () { return "Xiaojianbang{" + "name='" + name + '\'' + ", age=" + age + '}' ; } }
反射操作属性 import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.Properties;public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception { String filePath = new File ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Class<?> cls1 = Xiaojianbang.class; Class<?> cls2 = new Xiaojianbang ().getClass(); Class<?> cls3 = Xiaojianbang.class.getClassLoader().loadClass(className); Class<?> cls4 = new Xiaojianbang ().getClass().getClassLoader().loadClass(className); System.out.println(cls1); System.out.println(cls2); System.out.println(cls3); System.out.println(cls4); System.out.println(int .class); System.out.println(Integer.TYPE); System.out.println(Integer.class); Method method = cls.getMethod(methodName); method.invoke(null ); new DemoI (){ @Override public void printInfo1 () { System.out.println("lelele" ); } }.printInfo1(); System.out.println("================================" ); System.out.println(Class.forName("Xiaojianbang" )); System.out.println(Class.forName("Xiaojianbang$Demo" )); System.out.println("Hello$1" ); System.out.println(DemoI.class); System.out.println(Thread.State.class); System.out.println(SuppressWarnings.class); System.out.println(int .class); System.out.println(Integer.class); System.out.println(void .class); String[] str1 = new String []{"xiaojianbang" }; String[][] str2 = new String [][]{{"xiaojianbang" }}; System.out.println(str1.getClass().getName()); System.out.println(String[].class); System.out.println(String[][].class); System.out.println("================================" ); Class<?> xiaojianbang = Class.forName("Xiaojianbang" ); Object o1 = xiaojianbang.newInstance(); System.out.println(o1); Constructor<?> constructor = xiaojianbang.getConstructor(String.class,int .class); Object o2 = constructor.newInstance("xiaojianbang" , 30 ); System.out.println(o2); Constructor<?> constructor1 = xiaojianbang.getDeclaredConstructor(String.class); constructor1.setAccessible(true ); Object o3 = constructor1.newInstance("xiaojianbang1" ); System.out.println(o3); System.out.println("================================" ); Field nameField = xiaojianbang.getField("name" ); String name = (String)nameField.get(o3); System.out.println(name); nameField.set(o3,"xiaojianbang2" ); name = (String) nameField.get(o3); System.out.println(name); Field sexField = xiaojianbang.getDeclaredField("sex" ); sexField.setAccessible(true ); boolean sex = (boolean )sexField.get(o3); System.out.println(sex); sexField.set(null ,true ); sex = (boolean )sexField.get(o3); System.out.println(sex); } } class Xiaojianbang { public String name; public int age; private static boolean sex; public Xiaojianbang () { } public Xiaojianbang (String name, int age) { this .name = name; this .age = age; } private Xiaojianbang (String name) { this .name = name; } public static void printInfo () { System.out.println("qq: 23458757" ); } public static void printInfo2 () { System.out.println("VX: 12345678" ); } class Demo { } @Override public String toString () { return "Xiaojianbang{" + "name='" + name + '\'' + ", age=" + age + '}' ; } }
反射操作方法 import java.io.File;import java.io.FileInputStream;import java.io.FileReader;import java.io.IOException;import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;import java.util.Properties;public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception { String filePath = new File ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Class<?> cls1 = Xiaojianbang.class; Class<?> cls2 = new Xiaojianbang ().getClass(); Class<?> cls3 = Xiaojianbang.class.getClassLoader().loadClass(className); Class<?> cls4 = new Xiaojianbang ().getClass().getClassLoader().loadClass(className); System.out.println(cls1); System.out.println(cls2); System.out.println(cls3); System.out.println(cls4); System.out.println(int .class); System.out.println(Integer.TYPE); System.out.println(Integer.class); new DemoI (){ @Override public void printInfo1 () { System.out.println("lelele" ); } }.printInfo1(); System.out.println("================================" ); System.out.println(Class.forName("Xiaojianbang" )); System.out.println(Class.forName("Xiaojianbang$Demo" )); System.out.println("Hello$1" ); System.out.println(DemoI.class); System.out.println(Thread.State.class); System.out.println(SuppressWarnings.class); System.out.println(int .class); System.out.println(Integer.class); System.out.println(void .class); String[] str1 = new String []{"xiaojianbang" }; String[][] str2 = new String [][]{{"xiaojianbang" }}; System.out.println(str1.getClass().getName()); System.out.println(String[].class); System.out.println(String[][].class); System.out.println("================================" ); Class<?> xiaojianbang = Class.forName("Xiaojianbang" ); Object o1 = xiaojianbang.newInstance(); System.out.println(o1); Constructor<?> constructor = xiaojianbang.getConstructor(String.class,int .class); Object o2 = constructor.newInstance("xiaojianbang" , 30 ); System.out.println(o2); Constructor<?> constructor1 = xiaojianbang.getDeclaredConstructor(String.class); constructor1.setAccessible(true ); Object o3 = constructor1.newInstance("xiaojianbang1" ); System.out.println(o3); System.out.println("================================" ); Field nameField = xiaojianbang.getField("name" ); String name = (String)nameField.get(o3); System.out.println(name); nameField.set(o3,"xiaojianbang2" ); name = (String) nameField.get(o3); System.out.println(name); Field sexField = xiaojianbang.getDeclaredField("sex" ); sexField.setAccessible(true ); boolean sex = (boolean )sexField.get(o3); System.out.println(sex); sexField.set(null ,true ); sex = (boolean )sexField.get(o3); System.out.println(sex); System.out.println("=================================" ); Method printInfo2 = xiaojianbang.getMethod("printInfo2" , String.class); String result = (String) printInfo2.invoke(o3,"这是传入的参数" ); System.out.println(result); Method printInfo1 = xiaojianbang.getDeclaredMethod("printInfo1" ); printInfo1.setAccessible(true ); printInfo1.invoke(null ); } } class Xiaojianbang { public String name; public int age; private static boolean sex; public Xiaojianbang () { } public Xiaojianbang (String name, int age) { this .name = name; this .age = age; } private Xiaojianbang (String name) { this .name = name; } private static void printInfo1 () { System.out.println("qq: 23458757" ); } public static String printInfo2 (String a) { System.out.println("VX: 12345678" +a); return "这是返回值" ; } class Demo { } @Override public String toString () { return "Xiaojianbang{" + "name='" + name + '\'' + ", age=" + age + '}' ; } }
Class类对象的其他方法
public class Hello { @SuppressWarnings({"all"}) public static void main (String[] args) throws Exception{ String filePath = new File ("" ).getCanonicalPath() + File.separator + "src\\demo.properties" ; Properties properties = new Properties (); properties.load(new FileInputStream (filePath)); String className = (String) properties.get("class" ); String methodName = (String) properties.get("method" ); System.out.println(className + "." + methodName); Class<?> cls = Class.forName(className); Class<?> cls1 = Xiaojianbang.class; Class<?> cls2 = new Xiaojianbang ().getClass(); Class<?> cls3 = Xiaojiangbang.class.getClassLoader().loadClass(className); Class<?> cls4 new Xiaojianbang ().getClass().getClassLoader().loadClass(className); System.out.println(cls1); System.out.println(cls2); System.out.println(cls3); System.out.println(cls4); System.out.println(int .class); System.out.println(Integer.TYPE); System.out.println(Integer.class); System.out.println("================================" ); System.out.println(Class.forName("Xiaojianbang" )); System.out.println(Class.forName("Xiaojianbang$Demo" )); System.out.println("Hello$1" ); System.out.println(DemoI.class); System.out.println(Thread.State.class); System.out.println(SuppressWarnings.class); System.out.println(int .class); System.out.println(Integer.class); System.out.println(void .class); String[] str1 = new String []{"xiaojianbang" }; String[][] str2 = new String [][]{{"xiaojianbang" }}; System.out.println(str1.getClass().getName()); System.out.println(String[].class); System.out.println(String[][].class); System.out.println("================================" ); new DemoI (){ @Override public void printInfo1 () { System.out.println("lelele" ); } }.printInfo1(); System.out.println("================================" ); System.out.println(Class.forName("Xiaojianbang" )); System.out.println(Class.forName("Xiaojianbang$Demo" )); System.out.println("Hello$1" ); System.out.println(DemoI.class); System.out.println(Thread.State.class); System.out.println(SuppressWarnings.class); System.out.println(int .class); System.out.println(Integer.class); System.out.println(void .class); String[] str1 = new String []{"xiaojianbang" }; String[][] str2 = new String [][]{{"xiaojianbang" }}; System.out.println(str1.getClass().getName()); System.out.println(String[].class); System.out.println(String[][].class); System.out.println("================================" ); Class<?> xiaojianbang = Class.forName("Xiaojianbang" ); Object o1 = xiaojianbang.newInstance(); System.out.println(o1); Constructor<?> consrtuctor = xiaojianbang.getConstructor(String.class,int .class); Object o2 = constructor.newInstance("xiaojainbang" ,30 ); System.out.println(o2); Constructor<?> constructor1 = xiaojianbang.getDeclaredCostructor(String.class); constructor1.setAccessible(true ); Object o3 = constructor1.newInstance("xiaojianbang1" ); System.out.prinln(o3); System.out.println("================================" ); Field nameField = xiaojianbang.getField("name" ); String name = (String)nameField.get(o3); System.out.println(name); nameField.set(o3,"xiaojianbang2" ); name = (String) nameField.get(o3); System.out.println(name); Field sexField = xiaojianbang.getDeclaedField("sex" ); sexField.etAccessible(true ); boolean sex = (boolean )sexField.get(o3); System.out.println(sex); sexField.set(null ,true ); sex = (boolean )sexField.get(o3); System.out.println(sex); System.out.println("================================" ); Method printInfo2 = xiaojianbang.getMethod("printInfo2" ,String.class); String result = (String) printInfo.invoke(o3,"这是传入的参数" ); System.out.println(result); Method printInfo1 = xiaojianbang.getDeclaredMethod("printInfo10" ); printInfo1.setAccessible(true ); printFinf1.invoke(null ); System.out.println(xiaojianbang.getSuperclass()); System.out.println(DemoI.class.getInterfaces()); Class<?> []interfaces = xiaojianbang.getInterfaces(); System.out.println(interfaces.length); System.out.println(interfaces[0 ]); Class<?> [] classes = xiaojianbang.getDeclaredClasses(); System.out.println(classes.length); } } class Xiaojianbang implements DemoI { public String name; public int age; private static boolean sex; public Xiaojianbang () { } public Xiaojianbang (String name, int age) { this .name = name; this .age = age; } private Xiaojianbang (String name) { this .name = name; } private static void printInfo10 () { System.out.println("qq: 23458757" ); } public static String printInfo2 (String a) { System.out.println("VX: 12345678" +a); return "这是返回值" ; } @Override public void printInfo1 () { } class Demo { } @Override public String toString () { return "Xiaojianbang{" + "name='" + name + '\'' + ", age=" + age + '}' ; } }
打印类的结构信息 public class Hello { @SuprressWarnings({"all"}) public static void main (String[] args) throws Exception{ Class<?> xiaojianbang = Class.forName("Xiaojianbang" ); Field[] declaredFields = xiaojianbang.getDeclaredFields(); for (Field declaredField:declaredFields){ System.out.println(declaredField.getName()); System.out.println(declaredField.getModifiers()); System.out.println(declaredField.getType()); } System.out.println(Modifier.isPrivate(1 )); System.out.println("=============================" ); Method[] declaredMethods = xiaojianbang.getDeclaredMethod(); for (Method declaredMethod : declaredMehtods){ System.out.println(declaredMethod.getName()); } System.out.println("=================================" ); Constructor<?>[] declaredConstructor = xiaojianbang.getDeclaredConstructors(); for (Constructor deeclaredConstructor : declaredCOnstructors){ System.out.prinln(declaredConstructor.getName()); } System.out.println("==================================" ); Class<?> superclass = xiaojianbang.getSuperclass(); superclass.getDeclaredFields(); superclass.getDeclaredMethods(); superclass.getDeclaredConstructors(); Class<?>[] interfaces = xiaojianbang.getInterfaces(); Class<?>[] declaredClasses = xiaojianbang.getDeclaredClasses(); declaredClasses[0 ].getDeclaredFields(); declaredClasses[0 ].getDeclaredMethods(); declaredClasses[0 ].getDeclaredConstructors(); Class<?>[] declaredClasses1 = declaredClasses[0 ].getDeclaredClasses(); } } class Xiaojianbang implements DemoI { public String name; public int age; private static boolean sex; public Xiaojianbang () { } public Xiaojianbang (String name, int age) { this .name = name; this .age = age; } private Xiaojianbang (String name) { this .name = name; } private static void printInfo10 () { System.out.println("qq: 23458757" ); } public static String printInfo2 (String a) { System.out.println("VX: 12345678" +a); return "这是返回值" ; } @Override public void printInfo1 () { } class Demo { } @Override public String toString () { return "Xiaojianbang{" + "name='" + name + '\'' + ", age=" + age + '}' ; }