Java课所有代码汇总
================================================================ package cn.buaa.helloworld;
public class Ex {
public static void main(String[] args) {
} //continue语句用法练习:输出101~200之间的素数 //标记一个数是否为素数 boolean flag = true; long begin = System.currentTimeMillis(); for(int i = 101; i <= 200; i++){ } long end = System.currentTimeMillis(); System.out.println("time: " + (end - begin)); flag = true; for(int j = 2; j < i; j++){ } //若为素数则打印 if(flag){ } System.out.println(i); //若 i 可以被 j整除 if(i % j == 0){ } flag = false; break;
package cn.buaa.helloworld;
import java.util.Scanner;
public class HelloWorld {
static int i = 10;
double PI = Math.PI;
double x = Math.sin(Math.PI); {
}
/**
* @param args
*/
public static void main(String[] args) {
//合法的标识符 String name = ""; String $address = ""; String _school = ""; //基本数据类型 byte b = 12; byte b1 = 125; // TODO Auto-generated method stub System.out.println("HelloWorld.."); //不合法的 //String 5name = ""; //String name_2# = ""; //String public = ""; System.out.print("HelloWorld..");
//注意不能超过范围 //byte b2 = 146; short s = 12; //编译出错, 浮点型默认为 double, 不能直接把 double 类型赋值给 float 类型. //float f = 12.34; float f = 12.34f; //字符型 char c = 'A'; System.out.println(c); System.out.println(c + 12); char c2 = '我'; //转义字符 System.out.println("Hello\nWorld"); //Java 的类型转换 //隐式的类型转换 float f2 = 12; //显式(强制)的类型转换 float f3 = (float)12.34; //数据类型自动提升 double d2 = f3 + 12.34;
//变量的生命周期和作用域 int j = 12; System.out.println(j); { } //System.out.println(m); //输出 System.out.println(""); //输入 //1. 输入一个字符串 Scanner sc = new Scanner(System.in); System.out.println("请输入年级: "); String input = sc.next(); System.out.println("年级: " + input); //2. 输入一个 int 类型 System.out.println("年纪: " ); int age = sc.nextInt();
System.out.println(j + 12 + i); int m = 12;
}
System.out.println("年龄: " + age); System.out.println("薪资: "); double salary = sc.nextDouble();
//单行注释
/*
* 多行注释
*
*
*
*/
package cn.buaa.helloworld;
public class TestFor {
public static void main(String[] args) {
//1. 从 1 打印到 100 //i++ 等价于: i=i+1 for(int i = 1; i <= 100; i++){ System.out.println(i);
} //while 循环 int i = 101; while(i <= 100){ } i = 101; //do...while 循环 do{ System.out.println("**>" + i); i++; System.out.println("-->" + i); i++; }while(i <= 100); //2. i++ vs ++i i = 100; //i = i + 1; System.out.println(i++); //100: i++ 此时 i 的值为 i 本身的值, 之后为 i + 1 的值 System.out.println(i); //101 i = 100; System.out.println(++i); //100: ++i 此时 i 的值为 i 即为 i+ 1 的值. System.out.println(i); //101 //break
}
//1.输入一个整数, 从 1 循环到 100, 若输入的整数为 55, 则 打印到 55 退出循环 int a = 55; for(int j = 1; j <= 100; j++){ } //continue //2.输入一个整数, 从 1 循环到 100, 若输入的整数为 55, 则跳过55 继续打印 a = 55; for(int j = 1; j <= 100; j++){ } if(a == 55 && j == a){ } System.out.println("--->" + j); continue; System.out.println(j); if(a == 55 && j == a){ } break;
package cn.buaa.helloworld;
import java.util.Scanner;
public class TestIf {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub int i = 10; if(i > 10) else /** * 输入一个年龄, 根据年龄打印: * * 请输入年龄: * * age <= 14: 输出 "小学生" * age <= 17: "初中生" * age <= 20: "高中生" * age <= 24: "大学生" * 否则 "就业" * */ Scanner sc = new Scanner(System.in); System.out.println("i <= 10"); System.out.println("i > 10");
System.out.println("请输入年龄:" ); int age = sc.nextInt(); String res = null; if(age <= 14) // 14 < age <= 17 else if(age <= 17) res = "初中生"; res = "小学生"; else if(age <= 20) res = "高中生"; else if(age <= 24) else System.out.println(res); //不能直接使用连续的比较运算符: //17 >= age > 14 if(17 >= age && age > 14){ } /** * 由键盘输入三个整数分别存入变量num1、num2、num3,
res = "大学生"; res = "就业";
}
* 对它们进行排序,并且从小到大输出。 */ int num1 = 12; int num2 = 10; int num3 = 11; if(num1 <= num2){ } //三目运算符 //求两个数的最大值 int m = 12; int n = 13; int z = m > n ? m : n; System.out.println(z); if(num2 <= num3){ } if(num3 <= num1){ } //num3, num1, num2 //num1, num2, num3
package cn.buaa.helloworld;
import java.util.Scanner;
public class TestIf {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub int i = 10; if(i > 10) else /** * 输入一个年龄, 根据年龄打印: * * 请输入年龄: * * age <= 14: 输出 "小学生" * age <= 17: "初中生" * age <= 20: "高中生" * age <= 24: "大学生" System.out.println("i <= 10"); System.out.println("i > 10");
* 否则 "就业" * */ Scanner sc = new Scanner(System.in); System.out.println("请输入年龄:" ); int age = sc.nextInt(); String res = null; if(age <= 14) // 14 < age <= 17 else if(age <= 17) res = "初中生"; res = "小学生"; else if(age <= 20) res = "高中生"; else if(age <= 24) else System.out.println(res); //不能直接使用连续的比较运算符: //17 >= age > 14 if(17 >= age && age > 14){
res = "大学生"; res = "就业";
} /** * 由键盘输入三个整数分别存入变量num1、num2、num3, * 对它们进行排序,并且从小到大输出。 */ int num1 = 12; int num2 = 10; int num3 = 11; if(num1 <= num2){ } //三目运算符 //求两个数的最大值 int m = 12; int n = 13; int z = m > n ? m : n; System.out.println(z); if(num2 <= num3){ } if(num3 <= num1){ } //num3, num1, num2 //num1, num2, num3
}
package cn.buaa.helloworld;
public class TestMethod {
//方法: 有返回值
static String addStr(String s1, String s2){
}
//方法: 没有返回值
static void printStr(String s1, String s2){
}
//方法: 没有返回值的方法可以加 return 吗? 可以加上 return static void testReturn(){
}
//方法: 没有返回值的方法可以加 return 吗?
String re = s1 + s2; return re; String re = s1 + s2; System.out.println("string: " + re); System.out.println("Return..."); //方法结束 return;
static void testReturn2(){
}
static void testReturn3(int age){
}
public static void main(String[] args) {
String str = addStr("hello"," World--"); System.out.println(str); printStr("Hi", " Java"); testReturn(); //运算符 System.out.println("Return..."); if(age == 12) System.out.println("----------------"); //方法结束 return; System.out.println("Return..."); //方法结束 return; //编译出错, 在 return 后边不能在写代码 //System.out.println("");
//1. + 可以拼字符串 String str2 = "abc" + "def"; System.out.println(str2); String str3 = "abc" + 12; System.out.println(str3); String str4 = "" + true + 12; System.out.println(str4); //把一个基本数据类型转换为字符串 int i = 123; String str5 = i + ""; //2. 取模, 求余 int j = 12 % 5; System.out.println(j); //3. / 对于整数相除, 将舍弃小数部分 j = 10 / 100; System.out.println(j); //4. 逻辑运算符 int m = 12; int n = 20; if(m > 10 || n/0 > 15){
System.out.println("m > 10 || n > 15");
//
//
//
} } //非短路逻辑运算符 //扩展赋值运算符 m = 100; //m = m + 100; m += 100; System.out.println(m); if(m > 10 | n/0 > 15){ } System.out.println("m > 10 || n > 15");
package cn.buaa.helloworld;
public class TestSwitch {
public static void main(String[] args) {
/** * 输入一个整数, 从 1 到 3, 若其他的输入 other * 若该整数为 1, 输出 one, ... */ int i = 1;
//
//
//
}
switch(i){ } long j = 12; //表达式的返回值必须是下述几种类型之一:int, byte, char, short, 枚举 switch(j){ } case 1: case 2: case 3: System.out.println("three"); break; System.out.println("two"); break; System.out.println("one"); //跳出 break; default: System.out.println("other"); break;
package cn.buaa.array;
public class Person {
private String name;
public String getName() {
}
public void setName(String name) {
} package cn.buaa.array;
import java.util.Random;
public class Students {
public static void main(String[] args) {
//创建20个学生对象 Student [] ss = null; //此时会抛出 NullPointerException //System.out.println(ss.length); ss = new Student[20]; Random random = new Random();
return name; this.name = name;
}
}
/**
* //对数组进行赋值 for(int i = 0; i < ss.length; i++){ } for(int i = 0; i < ss.length; i++){ } System.out.println("number: " + ss[i].number + ", state: " + ss[i].state + ", score: " + ss[i].score); //为数组的每一个元素赋值 ss[i] = new Student(); //为元素的属性赋值 ss[i].number = i + 1; ss[i].state = random.nextInt(10); ss[i].score = random.nextInt(100);
* 定义类Student,包含三个属性:学号number(int),年级state(int),
* 成绩score(int)。
* 创建20个学生对象,
* 学号为1到20,年级和成绩都由随机数确定,打印出3年级(state值为3)的学生信息。
*
*/
class Student{
int number;
int state;
int score;
package cn.buaa.array;
import java.lang.reflect.InvocationTargetException;
import mons.beanutils.BeanUtils;
public class TestArray {
public static void main(String[] args) throws IllegalAccessException, InvocationTargetException {
Person person = new Person(); BeanUtils.setProperty(person, "name", "Tom"); System.out.println(person.getName()); //打印一个杨辉三角 int [][] yh = new int[10][]; for(int i = 0; i < yh.length; i++){
} yh [i] = new int[i + 1]; yh[i][0] = 1; yh[i][i] = 1; if(i > 1){ } for(int j = 1; j < i; j++){ } yh[i][j] = yh[i-1][j-1] + yh[i-1][j]; //遍历二维数组 for(int i = 0; i < yh.length; i++){ } //二维数组 int [][] as = {{1,2}, {3,4}, {5,6}}; int [][] bs = new int [5][]; for(int i = 0; i < bs.length; i++){ } //int i = 10;
for(int j = 0; j < yh[i].length; j++){ } System.out.println(); System.out.print(yh[i][j] + " "); bs[i] = new int[i + 1];
//定义一个数组 int [] a = {1, 2, 4, 3, 5}; //int b [] = {1, 2}; //定义一个数组 int [] c = null; c = new int[10]; //length 为数组的长度 System.out.println(c.length); //对数组进行赋值 for(int i = 0; i < c.length; i++){ } //对数组进行遍历 for(int i = 0; i < c.length; i++){ } String[] strs = null; strs = new String[10];
c[i] = 10 + i; System.out.println(c[i]);
}
Ls3:
package cn.buaa.lsn3;
public class Boy {
private String name;
private Girl girl;
public Boy(String name, Girl girl) {
}
public String getInfo(){
}
public String getName() {
} }
package cn.buaa.lsn3;
this.name = name; this.girl = girl; //和这个女孩结婚 girl.marry(this); return "Boy's name is " + name + ", gf: " + girl.getName(); return name;
public class Dog {
public Dog(String name) {
}
}
package cn.buaa.lsn3;
public class Ex {
/**
* 定义三个重载方法max,第一个方法求两个int值中的最大值, * 第二个方法求两个double值中的最大值,
* 第三个方法求三个double值中的最大值,并分别调用三个方法。 *
*/
public static void main(String[] args) {
//max(2, 6); Ex ex = new Ex(); //调用哪个对象的 max 方法: 答: ex 的 // TODO Auto-generated constructor stub System.out.println("Dog: " + name);
}
ex.max(12.1, 12.2);
public int max(int i, int j){
}
public double max(double i, double j){
}
public double max(double i, double j, double z){
}
}
package cn.buaa.lsn3;
public class Girl {
private String name;
private Boy boy;
return i > j ? i : j; return i > j ? i : j; //调用 max(double, double) 方法 //调用的是哪个对象的 max 方法? 答: 当前对象的 max 方法. double a = max(i, j); double b = max(a, z); return b;
public void setName(String name) {
}
public String getName() {
}
public void marry(Boy boy){
}
}
package cn.buaa.lsn3;
public class Person {
public Person(int age, String name, Dog dog) {
}
public Person() {
this.name = name; return name; System.out.println("女孩结婚 with " + boy.getName()); super(); System.out.println("Person's constructor..."); this.age = age; this.name = name; this.dog = dog;
}
//属性 // TODO Auto-generated constructor stub
private int age = -2;
private String name = "unkonwn";
private Dog dog = new Dog("XingXing");
//方法
public void study(){
}
//不能利用返回值区分方法
//
//
//
public void study(String book){
}
public void study(String project, int year){
} public int study(){ } return 1; System.out.println("day day up...");
public void add(){}
public void add(int i, float j){}
public void add(float j, int i){}
//编写属性的 setter, getter 方法
public int getAge() {
}
public void setAge(int age) {
}
public String getName() {
}
public void setName(String name) {
} }
package cn.buaa.lsn3;
//利用面向对象的编程方法,设计类Circle计算圆的面积。 public class TestCircle {
return age; this.age = age; return name; this.name = name;
public static void main(String[] args) {
}
}
class Circle{
private int r;
public void setR(int r) {
} if(r <= 0){ } this.r = r; System.out.println("r 的值不能为负数!"); return; //创建对象 Circle c = new Circle(); //对属性进行赋值 c.setR(-2); //获取圆的面积 System.out.println(c.getArea()); //System.out.println(c.getArea(2));
public double getArea(){
}
public double getArea(int r){
}
}
package cn.buaa.lsn3;
public class TestGirl {
public static void main(String[] args) {
}
}
package cn.buaa.lsn3;
public class TestPerson { Girl girl = new Girl(); girl.setName("Jerry"); Boy boy = new Boy("Tom", girl); System.out.println(boy.getInfo()); //girl.marry(boy); return Math.PI * r * r; return Math.PI * r * r * r;
public static void main(String[] args) {
//
//
//
//
/* //声明一个 Person 变量 Person person = null; //为 person 赋值 person = new Person(); //为属性赋值 person.setAge(12); person.setName("Tom"); //调用方法 person.study(); System.out.println(person.getAge()); System.out.println(person.getName()); */ Dog dog = new Dog("YueYue"); Person p2 = new Person(13, "Jerry", dog); { } Person p2 = new Person();
} Ls4:
Java包 System.out.println(p2.getAge()); System.out.println(p2.getName());
package cn.buaa.java;
public class Address {
//访问权限最为严格, 只限于当前类 private String city;
//限于当前包
String street;
//可以跨包, 但只能被子类访问 protected String code;
//可以挎包, 被直接访问
public int years;
public Address(String city){
}
}
System.out.println("City: " + city);
package cn.buaa.java;
public class Circle {
private double radius;
public Circle(double radis) {
}
public double getRadius() {
};
public void setRadius(double radius) {
}
public double findArea(){
} }
package cn.buaa.java;
public class Circle {
private double radius; return Math.PI * this.radius * this.radius; this.radius = radius; return radius; // TODO Auto-generated constructor stub this.radius = radis;
public Circle(double radis) {
}
public double getRadius() {
};
public void setRadius(double radius) {
}
public double findArea(){
} }
package cn.buaa.java;
/**
* 修改练习1中定义的Cylinder类,
* 在Cylinder类中覆盖findArea()方法,计算圆柱的表面积。 *
* 考虑:findVolume方法怎样做相应的修改?
* 在TestCylinder类中创建Cylinder类的对象,
* 设置圆柱的底面半径和高,并输出圆柱的表面积和体积。 * @author Administrator
// TODO Auto-generated constructor stub this.radius = radis; return radius; this.radius = radius; return Math.PI * this.radius * this.radius;
*
*/
public class Cylinder extends Circle {
private double length;
public void setLength(double length) {
}
public double getLength() {
}
public Cylinder(double radius, double length) {
}
//在Cylinder类中覆盖findArea()方法,计算圆柱的表面积。 public double findArea() {
}
//获取体积
public double findVolume() {
return super.findArea() * length;
this.length = length; return length; // TODO Auto-generated constructor stub super(radius); this.length = length; // TODO Auto-generated method stub return super.findArea() * 2 + Math.PI * getRadius() * 2 * length;
} }
package cn.buaa.java;
public class Dog {
public Dog(String name) {
}
}
package cn.buaa.java;
/**
* (2)定义类Kids1继承ManKind,并包括 成员变量int yearsOld; * 方法printAge()打印yearsOld的值。
*
* @author Administrator
*
* 修改练习3中定义的类Kids1中employed()方法,
* 在该方法中调用父类ManKind的employed()方法,\
* 然后再输出“but Kids should study and no job.”
*
*
*/
public class Kids1 extends ManKind{
// TODO Auto-generated constructor stub System.out.println("Dog: " + name);
private int yearsOld;
public void printAge(){
}
public int getYearsOld() {
}
public void setYearsOld(int yearsOld) {
}
public void employeed() {
}
public static void main(String[] args) {
Kids1 kids1 = new Kids1(); kids1.setSalary(1000); kids1.setSex(0); kids1.setYearsOld(23); kids1.printAge(); kids1.employeed(); kids1.manOrWoman(); super.employeed(); System.out.println("but Kids should study and no job."); this.yearsOld = yearsOld; return yearsOld; System.out.println("yearsOld: " + yearsOld);
}
}
package cn.buaa.java;
/**
* .(1)定义一个ManKind类,
* 包括 成员变量int sex和int salary; 方法void * manOrWorman():根据sex的值显示“man” * (sex==1)或者“women”(sex==0); 方法void * employed():根据salary的值显示“no job” * (salary==0)或者“ job”(salary!=0)。
*
*/
public class ManKind {
private int sex;
private int salary;
public int getSex() {
}
public void setSex(int sex) {
}
this.sex = sex; return sex;
public int getSalary() {
}
public void setSalary(int salary) {
}
public void employeed(){
}
public void manOrWoman(){
}
}
package cn.buaa.java;
public class Person { if(sex == 1) System.out.println("man"); if(salary == 0) else System.out.println("job"); System.out.println("no job"); this.salary = salary; return salary; else if(sex == 0) else System.out.println("error"); System.out.println("woman");
private String name;
int age;
private Dog dog = new Dog("Dog1...");
public Person(Dog dog) {
}
//
//
//
//
//
public void setName(String name) {
}
public String getName() {
}
public String getInfo(){
}
public void add(){} return "^^name: " + name + ", age: " + age; return name; this.name = name; public Person(int age) { } // TODO Auto-generated constructor stub this.age = age; System.out.println("Person..."); System.out.println("Person...");
public void add(int i){} }
package cn.buaa.java;
public class Student extends Person{
String school;
private Address address = new Address("City1");
//
//
//
//
//
public Student(Address address) {
}
//在子类的方法中调用父类被重写的方法, 即调用父类的 getInfo() 方法 public String getInfo(){
// return "name: " + getName() + ", age: " + age //调用父类的构造器 super(new Dog("Dog3...")); System.out.println("Student..."); public Student(int age){ } //在构造方法中调用重载的其他构造方法. this();
//
}
//
//
//
} + ", school: " + school; return super.getInfo() + ", school: " + school; public int add(){ } return 0;
package cn.buaa.java;
public class TestCylinder {
public static void main(String[] args) {
}
}
package cn.buaa.java;
public class TestStudent {
public static void main(String[] args) {
//
//
//
Dog dog = new Dog("Dog2..."); Person person = new Person(dog); Cylinder cylinder = new Cylinder(2, 2); System.out.println(cylinder.findVolume());
//
//
//
//
//
//
}
/** Student stu = new Student(new Address("Address2")); Address address = new Address(""); address.street = ""; stu.school = "BUAA"; stu.age = 12; stu.setName("Tom"); String info = stu.getInfo(); System.out.println(info);
* Address2
* Dog3...
* Dog1...
* Person...
*
* City1
* Student...
*
*/ }
Java2包:
package cn.buaa.java2;
import cn.buaa.java.Address;
public class City extends Address{
public City() {
}
public void test(){
}
}
package cn.buaa.java2;
public class Man extends Person{
int age;
public void work(){
} }
package cn.buaa.java2; System.out.println("Man work..."); this.code = ""; Address address = new Address(""); super("");
public class Person {
String name;
public void work(){
}
/**
* 重写 equals 方法, 当 name 属性相同即返回 true */
public boolean equals(Object obj) {
} boolean result = false; //1. 判断 obj 是否为 Person 类型, 若不是 Person 类型, 直接返回 false if(obj instanceof Person){ } System.out.println("result: " + result); return result; //2. 若是 Person 类型, 把 obj 对象强转为 Person 类型 Person p = (Person) obj; //3. 比较当前对象的 name 属性和 2 的 name 属性是否相同 //result = name == p.name; result = name.equals(p.name); System.out.println("Person work...");
public String toString() {
}
//
//
//
//
}
package cn.buaa.java2;
import cn.buaa.java.Address;
public class TestPerson {
public static void testPersonType(Object person) {
/** // System.out.println(person instanceof Person); // 检测 Person 对象的类型: 若传入的对象为 Person 类型, 打印 Person,,, // 若传入的对象类型为 Man: 打印 Man... // 若传入的对象类型为 Woman: 打印 Woman... // System.out.println(person); public String toString() { } // TODO Auto-generated method stub return "[Person] name:" + name; return "Person [name=" + name + "]";
}
* * 要求x所属的类与类A必须是子类和父类的关系,否则编译错误。 */ //System.out.println(new Man() instanceof new Woman()); //x instanceof A:检验x是否为类A的对象,返回值为boolean型。 //如果x属于类A的子类B,x instanceof A值也为true。 System.out.println(person instanceof Man);
public static void main(String[] args) {
/** * 访问控制 */ Address address = new Address(""); address.years = 12; /** * toString() 方法: 继承自 Object 类, 返回一个字符串: 全类名@哈希码 */ Person person3 = new Person(); person3.name = "Jerry"; System.out.println(person3.toString());
//希望: toString 方法返回有意义的字符串: 对于 Person 类, 返回: //[Person] name = xxxx. /** * == 和 equals() 方法 */ //比较两个 Person 对象是否为同一对象 Person person1 = new Person(); Person person2 = new Person(); // ==: 比较两个对象是否为同一对象: 内存地址是否相同 System.out.println("^^^" + (person1 == person1)); //true System.out.println("^^^" + (person1 == person2)); //false person1.name = "Tom"; person2.name = "Tom"; //默认情况下, equals 方法比较两个对象的内存地址是否相同. //希望: Person 类重写 equals 方法, 当 name 属性相同即返回 true System.out.println("~~~" + person1.equals(person2)); //false String s1 = new String("abcd"); String s2 = new String("abcd"); System.out.println("^^^" + (s1 == s2)); //false //String 类重写了 equals 方法, 若字符串相同即返回 true
System.out.println("~~~" + s1.equals(s2)); //true /** * instanceof 运算符 */ testPersonType(new Person()); testPersonType(new Man()); testPersonType(new Woman()); /** * 多态 */ Person p = new Person(); Man m = new Man(); m.name = ""; m.age = 12; // 多态: 父类类型的变量可以指向子类的对象 Person p2 = new Man(); p2.name = ""; // 编译时 p2 为 Person 类型,而方法的调用是在运行时确定的, // 所以调用的是 Man 类的 work()方法。——动态绑定 // 或称为 "虚拟方法调用" p2.work();
} } // 编译不通过: 一个引用类型变量如果声明为父类的类型, // 但实际引用的是子类对象,那么该变量就不能再访问子类中添加的属性和方法 // p2.age = 12; // 父类对象不能直接赋给子类的引用变量 // Man m2 = new Person(); // 在继承情况下, 类型的强制转换 Man m3 = (Man) p2; // p3 本来就是 Woman 对象, 所以运行通过. Person p3 = new Woman(); Woman w = (Woman) p3; // 编译通过: p2 是一个 Person 对象, 而 Person 对象可能为 Woman 类型. // 运行出错: p2 实际上是一个 Man 对象, 所以运行时出错 // Woman w2 = (Woman) p2; //无继承关系的引用类型间的转换是非法的 //Man m2 = new Woman(); //Object类是所有Java类的根父类 Object o1 = new Person();
package cn.buaa.java2; public class Woman extends Person{ }
Java3包:
package cn.buaa.java3;
public class Circle extends GeometricObject{
private double radius;
public Circle() {
}
public Circle(double radius) {
}
public Circle(double radius, String color,
}
public double getRadius() {
return radius;
this.radius = 1; this.radius = radius; double weight) { super(color, weight); this.radius = radius;
}
public void setRadius(double radius) {
}
public double findArea(){
}
public boolean equals(Circle obj) {
}
public String toString() {
} }
package cn.buaa.java3;
public class GeometricObject {
protected String color;
protected double weight;
public GeometricObject() {
// TODO Auto-generated constructor stub color = "white"; weight = 1.0; return "radius: " + radius; return this.radius == obj.getRadius(); return Math.PI * radius * radius; this.radius = radius;
}
public GeometricObject(String color, double weight) {
}
public String getColor() {
}
public void setColor(String color) {
}
public double getWeight() {
}
public void setWeight(double weight) {
}
}
package cn.buaa.java3;
public class TestCircle { this.weight = weight; return weight; this.color = color; return color; super(); this.color = color; this.weight = weight;
public static void main(String[] args) {
}
}
package cn.buaa.java3;
import java.util.ArrayList;
import java.util.List;
public class TestWrapper {
public static void main(String[] args) {
int i = 10; //包装类: //JDK1.4 时, 集合对象不能不放入基本数据类型\ //JDK 1.5 后, 系统提供了自动装箱技术 Circle circle1 = new Circle(); Circle circle2 = new Circle(); System.out.println(circle1); System.out.println(circle2); System.out.println(circle1 == circle2); //false System.out.println(circle1.equals(circle2)); //true
}
Ls5: //装箱: 把基本数据类型包装为对应的包装类类型. //Integer integer = new Integer(i); List list = new ArrayList(); /* list.add(new Integer(i)); Object obj = list.get(0); System.out.println(obj instanceof Integer); */ list.add(i);
package cn.buaa.java.inner;
public class OuterClass {
private int outerNumber;
private int innerNumber = 10;
//类中的内部类
class InnerClass{
}
} private int innerNumber = 20; public void innerTest(){ } //1. 访问外部类的属性 outerNumber = 100; //2. 访问内部类的属性 innerNumber = 200; //3. 访问外部类同名的属性 OuterClass.this.innerNumber = 100;
package cn.buaa.java.inner;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class TestInnerClass {
public static void main(String[] args) {
//如何创建非静态内部类的对象 OuterClass oc = new OuterClass(); OuterClass.InnerClass oi = oc.new InnerClass(); //方法内的内部类. 不能被外部访问. class MyInvocationHandler implements InvocationHandler{ } @Override public Object invoke(Object proxy, Method method, Object[] args) } throws Throwable { // TODO Auto-generated method stub return null; //第三个参数是一个接口 InvocationHandler 的实现类的对象 //而该实现类并不具有通用性: 每次调用 Proxy.newProxyInstance //时其实现类都不同. Proxy.newProxyInstance(TestInnerClass.class.getClassLoader(), new Class[]{}, new InvocationHandler(){
@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub
}
} }); } return null;
package cn.buaa.java;
public class Circle {
protected double radius;
public void setRadius(double radius) {
}
public double getRadius() {
}
}
package cn.buaa.java;
public class ComparableCircle extends Circle implements CompareObject {
/** return radius; this.radius = radius;
* 在ComparableCircle类中给出接口中方法compareTo的实现体, * 用来比较两个圆的半径大小。
*/
//若两个圆的半径相同, 返回 0
//若当前对象的半径较大, 返回 1
//若当前对象的半径较小, 返回 -1
//若 o 不是一个 Circle 类型, 返回 -2
public int compareTo(Object o) {
}
}
//1. 判断 o 的类型 if(!(o instanceof Circle)){ } //2. 若 o 为 Circle, 则进行类型的强制转换, 转换为 Circle 对象 Circle c = (Circle) o; //3. 进行比较 if(radius > c.getRadius()) return 1; return -2; else if(radius == c.getRadius()) else return -1; return 0;
package cn.buaa.java;
public interface CompareObject {
public int compareTo(Object o);
}
package cn.buaa.java;
public class Dog {
public Dog(String name) {
}
}
package cn.buaa.java;
/**
* 所谓类的单态设计模式,就是采取一定的方法保证在整个的软件系统中, * 对某个类只能存在一个对象实例
*
* @author Administrator
*
*/
public class SingleTon { // TODO Auto-generated constructor stub System.out.println("人类的好朋友..." + name);
//1. 不能在類的外部直接通過构造方法创建类的实例: 构造方法私有化
private SingleTon(){}
//2. 在类的内部创建类的实例, 该属性需要被外部访问, 且访问时外部没有当前类的对象 //所以需要把该属性声明为 static 属性
//静态属性只被初始化一次
private static SingleTon instance = new SingleTon();
//3. 一般而言, 非常量不应直接被外部访问, 应该通过方法进行访问
//1). 属性私有化
//2). 提供方法返回属性值
public static SingleTon getInstance() {
}
}
package cn.buaa.java;
public class TestAbstract {
public static void main(String[] args) {
}
return instance; //以下代码意味着每调用一次该方法都会返回一个被新创建的对象. //return new SingleTon(); //new Servlet();
}
//任何 Service 的子类都必须重写 service() 方法.
//因为每次处理的请求是不同的, 所以无法编写统一的 service() 方法 //有抽象方法的类, 一定是抽象类
//抽象类中, 可以没有抽象方法
//不能直接创建抽象类的对象
abstract class Servlet{
//该方法只需声明, 不要实现. 可以定义为抽象方法
abstract void service();
void test(){}
int i;
}
//子类一定要实现父类的抽象方法
class HelloServlet extends Servlet{
void service() {
}
// TODO Auto-generated method stub
}
package cn.buaa.java;
public class TestComparableCircle {
public static void main(String[] args) {
}
}
package cn.buaa.java;
public class TestFinal {
public static void main(String[] args) {
}
int i = 10;
void test(){ ComparableCircle c = new ComparableCircle(); c.setRadius(12); ComparableCircle c2 = new ComparableCircle(); c2.setRadius(13); System.out.println(c.compareTo(c2));
}
i = 12;
//用 final 修饰的属性是一个常量, 不能被修改 final int j = 12;
int x;
//常量必须在声明时被初始化
final int y = 10;
//或在构造器中被初始化
final int z;
public TestFinal() {
}
// TODO Auto-generated constructor stub z = 10;
//或在非静态代码块中初始化
final int m;
{
}
void test2(){
//编译出错,
m = 12;
}
}
//j = 12;
//final 修饰的类不能被修改 --- 不能被继承 final class Person{
void test(){}
//final 修饰的方法不能被修改, 不能被子类重写 final void test2(){}
}
/*
class Man extends Person{
void test(){}
//void test2(){}
} */
package cn.buaa.java;
/**
* interface
*
*
* @author Administrator
*
*/
public class TestInterface {
public static void main(String[] args) {
}
}
/**
* 接口: 更彻底的抽象类, 在其中只有抽象方法和常量. * @author Administrator
*
*/
interface Servlet2{
//默認類型为 public abstract
void init();
//在接口中不能提供方法的实现, 编译出错
//
//在接口中只能定义常量, 默认修饰为 public static final //int i;
int i = 12;
void destroy();
} void service(){} A a = new C();
//实现接口使用 implements 关键字, 若实现类中有未被实现的方法, 则该类需声明为抽象类 abstract class GenericServlet implements Servlet2{
@Override
public void init() {
}
}
interface A{
void a();
}
//接口之间可以有继承关系
interface B extends A{
void b();
}
//一个类既要继承一个类, 又要实现一个接口,
//先继承, 后实现, 且可以实现多个接口, 多个接口用 , 分隔
class C extends GenericServlet implements A, B{
@Override
public void a() { // TODO Auto-generated method stub
}
// TODO Auto-generated method stub
@Override
public void destroy() {
}
@Override
public void b() {
}
}
package cn.buaa.java;
public class TestSingleTon {
public static void main(String[] args) { //
//
SingleTon s1 = SingleTon.getInstance(); SingleTon s2 = SingleTon.getInstance(); //SingleTon s3 = new SingleTon(); SingleTon s1 = new SingleTon(); SingleTon s2 = new SingleTon(); // TODO Auto-generated method stub // TODO Auto-generated method stub
}
} System.out.println(s1 == s2); System.out.println(args.length); for(int i = 0; i < args.length; i++){ } System.out.println(args[i]);
package cn.buaa.java;
public class TestStatic {
private static Dog dog2 = new Dog("Jerry");
//静态代码块: 静态初始化
static{
}
private Dog dog = new Dog("Tom");
{
}
System.out.println("static block..."); System.out.println("no staic block...");
public TestStatic() {
}
//成员变量, 每一个对象都有一个单独的副本, 互相不受影响.
//为了达到目的, 需要使 count 变为类变量, 为为一个对象共享, 而不是独有. private int count = 0;
//被 static 修饰的变量称为类变量
//可以由类直接访问, 而不需要对象
private static int count2 = 0;
//实例方法访问类变量(count2)的情况: OK
//访问成员变量(count): OK
public void test1(){
}
//类方法访问类变量的情况: OK count2 = 10; count = 10; System.out.println("TestStatic...."); // TODO Auto-generated constructor stub count++; count2++;
//访问成员变量(count): NO!!!
//在static方法内部只能访问类的static属性,不能访问类的非static属性。 public static void test2(){
}
public int getCount() {
}
//static 修饰的方法称为静态方法
public static int getCount2() {
}
//统计创建了多少个 TestStatic 类的对象
public static void main(String[] args) {
TestStatic ts4 = new TestStatic(); /* System.out.println(TestStatic.count2); TestStatic ts1 = new TestStatic(); TestStatic ts2 = new TestStatic(); TestStatic ts3 = new TestStatic(); return count2; return count; count2 = 12; //count = 10;
}
Ls6:
package cn.buaa.java;
class EcDef extends RuntimeException{ public EcDef() {
}
public EcDef(String msg) {
}
}
public class EcmDe {
public static void main(String[] args) {
try {
System.out.println(ts1.getCount()); System.out.println(ts1.getCount2()); */ // TODO Auto-generated constructor stub // TODO Auto-generated constructor stub super(msg); //1. 接收输入的两个参数 String numStr1 = args[0]; String numStr2 = args[1];
}
//2. 把以上的两个字符串转换为整数类型 int i = Integer.parseInt(numStr1); int j = Integer.parseInt(numStr2); div(i, j); } catch (EcDef e) { System.out.println(e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("请输入足够多的整数. "); }catch (ArithmeticException e) { System.out.println("除数不能为 0"); }catch (NumberFormatException e) { } System.out.println("end..."); System.out.println("请输入整数");
public static void div(int i, int j){
//3. 对负数进行验证 if(i < 0 || j < 0){ } int r = i / j; System.out.print(r);
throw new EcDef("参与运算的数不能为负数");
}
}
package cn.buaa.java;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import javax.management.RuntimeMBeanException;
public class TestException {
public void test2(){
}
public static void main(String[] args) throws FileNotFoundException, NullPointerException { try { FileInputStream fis = new FileInputStream("haha.txt"); } catch (FileNotFoundException e) { } //打印异常信息 e.printStackTrace(); //包装 FileNotFoundException 异常对象, //抛出 RuntimeException throw new RuntimeException(e.getMessage());
//1.java.lang.NullPointerException TestException te = null; //te.test(); //2.java.lang.ArithmeticException //int i = 10 / 0; //3. ArrayIndexOutOfBoundsException int [] nums = {1,2,3}; //System.out.println(nums[3]); //4. java.lang.ClassCastException Object obj = new Integer(12); //te = (TestException) obj; //5. java.lang.NumberFormatException try{ String str = "as12"; int i = Integer.parseInt(str); }catch(Exception ex){ } //6. 编译时异常. FileInputStream fis = new FileInputStream("test.txt"); System.out.println(ex); System.out.println("出异常了...");
}
System.out.println("end...");
void test(){} }
package cn.buaa.java;
public class TestTryCatchFinally {
public static void main(String[] args) {
//
} //1. 先抓取小的异常, 再抓取大的异常. //2. 无论发生任何情况, finally 代码都会被执行! //3. 可以只有 try ... finally try { int i = 10 / 0; } catch(ArithmeticException e){ e.printStackTrace(); System.out.println(e.getMessage()); }finally{ } System.out.println("end..."); return; System.out.println("finally...");
Ls7:
package cn.buaa.java;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class TestCollection {
public static void main(String[] args) {
//有序的序列, 可以使用角标进行遍历 List list = new ArrayList(); list.add(2); list.add("a"); for(int i = 0; i < list.size(); i++){ } //无序的集合 Set set = new HashSet();
System.out.println(list.get(i));
set.add("2"); set.add(34); //不能使用角标进行遍历, 使用 Iterator 进行遍历 Iterator it = set.iterator(); while(it.hasNext()){ } //Map: 键值对的集合, 无序 Map<Object, Object> map = new HashMap(); map.put("a", "one"); map.put("b", "two"); map.put("c", "three"); //得到键的集合对应的 Iterator Iterator it2 = map.keySet().iterator(); while(it2.hasNext()){ } //简单的遍历方式 Object key = it2.next(); Object value = map.get(key); System.out.println(key + "--" + value); Object obj = it.next(); System.out.println(obj);
}
} for(Entry entry: map.entrySet()){ } Object key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + "--" + value);
package cn.buaa.java;
import java.util.Random;
public class TestRandom {
public static void main(String[] args) {
}
}
package cn.buaa.java;
public class TestStringAndInteger {
public static void main(String[] args) {
Random random = new Random(); //获取 10 以内的一个随机值 int i = random.nextInt(10); System.out.println(i);
//String 是不可修改的字符序列 String str2 = "abcd"; str2 = str2.toUpperCase(); //String 池 String str3 = "abc"; String str4 = "abc"; System.out.println(str3 == str4); //true String str5 = new String("abcde"); String str6 = new String("abcde"); System.out.println(str5 == str6); //false System.out.println(str2); //比较两个字符串, 但不区分大小写 String str7 = "aBdEE"; String str8 = "abdee"; System.out.println(str7.equalsIgnoreCase(str8)); //true String str = "1235678"; int sum = 0; for(int i = 0; i < str.length(); i++){ char ch = str.charAt(i);
}
} } int j = Integer.parseInt(ch + ""); sum += j; System.out.println(sum);
package cn.buaa.java;
public class TestStringBuffer {
public static void main(String[] args) {
//没有线程要求, 执行效率更高. StringBuilder sbl = new StringBuilder(); sbl.append(""); sbl.delete(1, 2); sbl.replace(1, 2, "aa"); sbl.substring(2, 3); //线程安全的 StringBuffer sbf = new StringBuffer(); sbf.append("abc") .append("def") .append("egh"); //abcdefegh
}
} System.out.println(sbf); sbf.delete(2, 4); //abefegh 而不是 abfegh //一般的, 区间均为 [) System.out.println(sbf); sbf.replace(2, 4, "mn"); //abmnegh System.out.println(sbf); //mne String sub = sbf.substring(2, 5); System.out.println(sub);
package lesson7;
public class Card { private String face; private String suit;
public String getFace() {
}
public String getSuit() {
}
return face; return suit;
public Card(String face, String suit) {
}
public String toString(){
} }
package lesson7;
import java.util.*;
public class Puke {
private Card [] cards;
public Puke(){
}
public void printPuke(){
for(int i = 0; i < cards.length; i++){
this.face = face; this.suit = suit; return face + suit; cards = new Card[52]; String [] faces = {"红桃","黒桃","草花","方块"}; String [] suits = {"A","2","3","4","5","6","7","8","9","10","J","Q","K"}; for(int i = 0; i < faces.length; i++) for(int j = 0; j < suits.length;j++){ } cards[i*13 + j] = new Card(faces[i],suits[j]); System.out.print(cards[i] + "\t"); if((i +1 )%13 == 0 ) System.out.println();
}
}
public void shuffle(){
Card [] cardsTemp = new Card[52]; Random r = new Random(); int [] a = new int[52]; a[0] = r.nextInt(52); boolean flag = true; for(int i = 1; i < cards.length;){ } for(int i = 0; i < cards.length; i++){ } cardsTemp[i] = cards[a[i]]; a[i] = r.nextInt(52); for(int j = 0; j < i; j++){ } if(flag){ }else{ } flag = true; continue; i++; if(a[j] == a[i]){ } flag = false;
} } cards = cardsTemp;
package lesson7;
public class TestPuke {
public static void main(String[] args) {
}
Ls8:
package cn.buaa.java;
import java.util.Arrays;
import java.util.List;
public class TestArgs { Puke puke = new Puke(); System.out.println("洗牌以前:"); puke.printPuke(); puke.shuffle(); System.out.println("洗牌以后:"); puke.printPuke();
public static void main(String... aaa) {
}
}
package cn.buaa.java;
import java.util.ArrayList;
import java.util.List;
public class TestBoxing {
public static void main(String[] args) {
List list = new ArrayList(); List scores = null; scores = Arrays.asList(1, 2, 3, 4, 5); System.out.println(scores.size()); list.add(12);
//自动装箱
Integer i = 12; //Integer m = new Integer(12); //自动拆箱 int j = i;
}
} //int n = i.intValue(); Integer z = null; int y = z;
package cn.buaa.java;
public class TestEnum {
public static void main(String[] args) {
}
Season2 SPRING = Season2.SPRING; System.out.println(SPRING.seasonName); //Season2 s2 = new Season2(); //SPRING.seasonName = ""; //对枚举类进行遍历 for(Season2 s: Season2.values()){ } //得到特定的枚举类对象 Season2 s3 = Season2.valueOf(Season2.class, "SUMMER"); System.out.println(s3.getInfo()); System.out.println(s);
}
interface Desc{
String getInfo();
}
enum Season2 implements Desc{
SPRING("Spring"){
},
SUMMER("Summer"){
},
AUTUMN("Autumn"){
@Override public String getInfo() {
@Override public String getInfo() { } // TODO Auto-generated method stub return null; @Override public String getInfo() { } // TODO Auto-generated method stub return "夏天..."; // TODO Auto-generated method stub return null;
}
}, WINTER("Winter"){
};
final String seasonName;
Season2(String sn){
}
/*
@Override
public String getInfo() {
}
*/
}
@Override public String getInfo() { } // TODO Auto-generated method stub return null; this.seasonName = sn; switch(this){ } return seasonName; case SPRING: return "春天..."; case SUMMER: //... return "夏天...";
//实例有限而且固定的类, 在 Java 中被称为枚举类
class Season{
private final String seasonName;
//Season 只能有 4 个实例, 且每个实例的属性不能被改变 private Season(String seasonName){
}
public static final Season SPRING = new Season("Spring...");
public static final Season SUMMER = new Season("Summer..."); public static final Season AUTUMN = new Season("Autumn..."); public static final Season WINTER = new Season("Winter..."); }
package cn.buaa.java;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class TestForEach {
public static void main(String[] args) {
this.seasonName = seasonName;
List list = new ArrayList(); list.add(12); list.add(23); list.add("23"); for(Object obj: list){ } Set set = new HashSet(); for(Object obj: set){ } Map<Object, Object> map = new HashMap(); for(Entry entry: map.entrySet()){ } //使用 foreach 为数组和集合的元素赋值不能成功: int [] scores = new int[10]; System.out.println(obj); for(int i = 0; i < scores.length; i++){ }
int score = scores[i]; score = 90;
}
} //赋值失败! for(int score: scores){ } for(int score: scores){ } System.out.println(score); score = 90;
package cn.buaa.java;
import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List;
//定义一个泛型类 class Dao<T>{
void save(T t){
}
void delete(T t){
}
// //
T get(){
}
void update(T t){
}
}
class Person{}
class Student extends Person{}
class Product{}
public class TestGeneric {
static void addToCollection(List<? extends Person> list){
}
//定义一个printCollection方法, 只能处理Person或其子类 static void printCollection4(List<? extends Person> c) {
return null; //编译出错! //list.add(new Student());
for (Object e : c) {
System.out.println(e);
}
}
static void printCollection3(List<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
static void printCollection2(List<Object> c) {
for (Object e : c) {
System.out.println(e);
}
}
static void printCollection(Collection c) {
Iterator i = c.iterator();
for (int k = 0; k < c.size(); k++) {
System.out.println(i.next());
}
}
//定义一个泛型方法: 和当前类有没有泛型无关.
//一般地, 方法的泛型的声明放在返回值类型的前面. public static<E> E get(){
E e = null;
}
return e;
public static void main(String[] args) {
//泛型方法 Person p = get(); //泛型和继承 List<Person> persons = new ArrayList<Person>(); //List<Object> 並非 List<Person> 的父類 //printCollection2(persons); printCollection4(persons); //编译出错, 因为 printCollection4(List<? extends Person>) //只能处理 List 类型的参数, 且 List 的泛型参数为 Person //或其子类类型. //printCollection4(new ArrayList<Product>()); List<? extends Person> persons2 = new ArrayList<Person>(); //编译出错, 因为不知道要放入的对象是否为 Person 的某一个子类类型, //所以添加会出错. //persons2.add(new Person()); //使用自定义的泛型类 Dao<Person> dao = new Dao<Person>(); dao.save(new Person()); //Person p = dao.get();
Dao<Student> stuDao = new Dao<Student>(); Person p2 = new Student(); //如果Foo是Bar的一个子类型(子类或者子接口), //而G是某种泛型声明,那么G<Foo>是G<Bar>的子类型并不成立!! //Dao<Person> personDao = stuDao; //使用泛型 List<Integer> scores = new ArrayList<Integer>(); scores.add(12); scores.add(23); //编译不通过, 因为 scores 中只能存放 Integer 类型 //scores.add("12"); //因为使用泛型, 所以不需要再进行强制类型转化. int score = scores.get(1); /* List scores = new ArrayList(); scores.add(90); scores.add(89); scores.add(67); scores.add("20"); //int score = (Integer) scores.get(3);
}
} */
package cn.buaa.java;
import static java.lang.Math.*;
public class TestStaticImport {
public static void main(String[] args) {
}
Ls9:
package cn.buaa.java;
public interface Calculator {
void add(int i, int j);
void sub(int i, int j);
int mul(int i, int j);
int div(int i, int j);
System.out.println(PI); System.out.println(sin(PI / 3));
}
package cn.buaa.java;
public class CalculatorImpl implements Calculator {
@Override
public void add(int i, int j) {
}
@Override
public void sub(int i, int j) {
}
@Override
public int mul(int i, int j) {
}
@Override
public int div(int i, int j) { int z = i * j; return z; int z = i - j; System.out.println("result: " + z); int z = i + j; System.out.println("result: " + z);
}
} int z = i / j; return z;
package cn.buaa.java;
import java.util.Arrays;
public class CalculatorLoggingImpl implements Calculator {
@Override
public void add(int i, int j) {
}
@Override
public void sub(int i, int j) {
System.out.println("The method sub begins with " + Arrays.asList(i, j)); System.out.println("The method add begins with " + int z = i + j; System.out.println("The method add ends with " + z); System.out.println("result: " + z); Arrays.asList(i, j)); int z = i - j;
}
System.out.println("The method sub ends with " + z); System.out.println("result: " + z);
@Override
public int mul(int i, int j) {
}
@Override
public int div(int i, int j) {
} System.out.println("The method div begins with " + Arrays.asList(i, j)); System.out.println("The method mul begins with " + int z = i * j; System.out.println("The method mul ends with " + z); return z; Arrays.asList(i, j)); int z = i / j; System.out.println("The method div ends with " + z); return z;
}
package cn.buaa.java;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class CalculatorLoggingProxy {
//1. 被代理对象
private Object target;
//2. 在构造器中传入被代理对象
public CalculatorLoggingProxy(Object target) {
}
//3. 返回代理对象
public Calculator getProxyInstance(){
//利用代理创建一个 Calculator 对象 Calculator calculator = null; /** * loader: ClassLoader 类型的参数. 创建的对象由哪个类加载器进行加载 // TODO Auto-generated constructor stub this.target = target;
* 一般地, 和被代理对象使用同一个类加载器 * * interfaces: Class[] 类型. 创建的对象属于什么类型 * * h: InvocationHandler 类型. 指定调用代理对象方法时, * 改如何相应 * */ calculator = (Calculator)Proxy.newProxyInstance(
target.getClass().getClassLoader(), new Class[]{Calculator.class}, new InvocationHandler() { /** * proxy: Object 类型, 一般地, 不使用改参数 * 代表正在产生的那个代理对象. * method: Method 类型, 代表正在被调用的方法 * args: Object [] 类型, 正在调用的方法被传入的参数 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //System.out.println(proxy); String methodName = method.getName(); //打印前置通知 System.out.println("The method " +
} } }); } methodName + " begins with " + Arrays.asList(args)); //执行目标方法 Object value = method.invoke(target, args); //后置通知 System.out.println("The method " + methodName + return value; " ends with " + value); return calculator;
package cn.buaa.java;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(value={ElementType.METHOD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME)
public @interface HelloAnnotation {
String name() default "World";
}
package cn.buaa.java;
public class Person {
private String name = "Tom"; int age;
protected int salary;
public String address;
public Person() {
}
public void work(){
}
public void setName(String name) {
}
void setName(){}
public String getName() {
} return name; this.name = name; // TODO Auto-generated constructor stub System.out.println("Peron's constrctor...");
}
package cn.buaa.java;
import java.lang.annotation.Annotation; import java.util.List;
public class TestAnnotation {
@SuppressWarnings({ "unused", "rawtypes" }) public static void main(String[] args) {
}
}
class Person2{
@HelloAnnotation(name="Jerry") Person2 p = new Person2(); p.test(); List list = null; Class clazz = p.getClass(); HelloAnnotation ann = (HelloAnnotation) clazz.getAnnotation(HelloAnnotation.class); String name = ann.name(); System.out.println(name);
void work(){}
//标识方法为过期方法, 不建议使用
@Deprecated
void test(){}
}
class Man extends Person2{
//标识方法为从父类继承的方法
@Override
void work() {
} }
package cn.buaa.java;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class TestClass {
public static void main(String[] args) throws Exception {
Person person = new Person(); //1. 获取 Person 对应的 Class 对象 // TODO Auto-generated method stub super.work();
Class clazz = Person.class; //2. 获取 Person 类中的属性 //getFields 方法只能获取到 public 类型的属性 Field [] fields = clazz.getFields(); System.out.println(fields.length); //getDeclaredFields 可以获取到所有的属性 fields = clazz.getDeclaredFields(); System.out.println(fields.length); for(Field field: fields){ } System.out.println("\n\n"); /** * Class 的相关方法: * 1. 获取 Class: Class.forName(className); * 2. 创建类的实例: Class.newInstance(), * 改方法将调用类的无参数的构造器. * */ Class clazz1 = Person.class; Class clazz2 = person.getClass();
//获取属性的名字 System.out.println(field.getName());
String className = "cn.buaa.java.Person"; Class clazz3 = Class.forName(className); Person person2 = (Person) clazz3.newInstance(); System.out.println(person2); /** * Method 相关的方法 * 1. 获取指定的 Method: * Class.getDeclaredMethod(name, Class ... parameterTypes) * 2. 使方法可访问: Method.setAccessible(true) * 3. 调用 Method 对应的方法: Method.invoke(obj, Object ... args); * */ //Method: 表示类的方法 //获取指定的 Method 对象 Method method = Person.class .getDeclaredMethod("setName", String.class); System.out.println(method.getName()); //设置方法是可被访问的 method.setAccessible(true); //调用 Method 对象对应的方法 method.invoke(person, "Mike"); System.out.println(person.getName());
} System.out.println("\n\n"); /** * 和 Field 相关的方法 * 1. 获取指定的属性: getDeclaredField("name") * 2. 设置属性是可被访问的: field.setAccessible(true); * 3. 获取对象对应的属性值: field.get(obj); * 4. 设置对象对应的属性值: field.set(obj, value); * */ //Field: 表示类的属性. Field field = Person.class.getDeclaredField("name"); //1). 获取类的某个对象的属性值 System.out.println(field.getName()); //对于非 public 类型属性, 需要调用 setAccessble 方法, 设置 //其可被访问 field.setAccessible(true); Person obj = new Person(); Object value = field.get(obj); System.out.println(value); //2). 设置类的某个对象的属性值 field.set(obj, "Jerry"); System.out.println(obj.getName());
}
package cn.buaa.java;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class TestClassLoader {
public static void main(String[] args) throws Exception {
} ClassLoader cl = TestClassLoader.class.getClassLoader().getParent(); System.out.println(cl); Class clazz = cl.loadClass("mons.dbutils.DbUtils"); System.out.println(clazz); Properties props = new Properties(); InputStream inStream = TestClassLoader.class .getClassLoader() .getResourceAsStream("cn/buaa/java/db.properties"); props.load(inStream); String name = props.getProperty("name"); String password = props.getProperty("password"); System.out.println(name + ", " + password);
}
package cn.buaa.java;
import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
public class TestProxy {
public static void main(String[] args) {
//代理的目标对象 final Calculator target = new CalculatorImpl(); Calculator cal = new CalculatorLoggingProxy(target) //.... //利用代理创建一个 Calculator 对象 Calculator calculator = null; /** .getProxyInstance();
* loader: ClassLoader 类型的参数. 创建的对象由哪个类加载器进行加载 * 一般地, 和被代理对象使用同一个类加载器 * * interfaces: Class[] 类型. 创建的对象属于什么类型 * * h: InvocationHandler 类型. 指定调用代理对象方法时, * 改如何相应 * */ calculator = (Calculator)Proxy.newProxyInstance( target.getClass().getClassLoader(), new Class[]{Calculator.class}, new InvocationHandler() { /** * proxy: Object 类型, 一般地, 不使用改参数 * 代表正在产生的那个代理对象. * method: Method 类型, 代表正在被调用的方法 * args: Object [] 类型, 正在调用的方法被传入的参数 */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //System.out.println(proxy); String methodName = method.getName();
} } }); } //打印前置通知 System.out.println("The method " + //执行目标方法 Object value = method.invoke(target, args); //后置通知 System.out.println("The method " + methodName + return value; " ends with " + value); methodName + " begins with " + Arrays.asList(args)); System.out.println(calculator.getClass()); System.out.println(calculator instanceof Calculator); calculator.add(1, 2); calculator.sub(2, 1); calculator.mul(1, 2); calculator.div(2, 3);