读书人

day01Java基础增强

发布时间: 2012-09-18 16:21:42 作者: rapoo

day01Java基础加强
1.IDE简介设置快捷键 :windows -> preference -> General -> Keys

自动提示快捷键需要设置 Content Assist

?

好用的快捷键 :?

ctrl + 1:鼠标定位出错地方附近使用,提示各种解决方法

alt + 上下:换行

ctrl + alt + 上下 :拷贝当前行

shift + 回车:在当前行的下面新增一行空白,光标定位到新行

shift + ctrl + 回车:光标所在行新增一行空白行,原有内容下移一行,光标定位到新行

?

全局字体样式设置 :windows -> preference -> General -> Appearance -> Basic -> Text Font

?

?

2.Junit的简单使用

?

import org.junit.*;public class Demo {//所有测试的方法都是public方法@BeforeClass//只执行一次,标记的方法中最先执行,且为静态public static void powerOn () {System.out.println("@BeforeClass");}@Before//在每个标志了@Test的方法之前执行public void openDir() {System.out.println("@Before");}@Test//需要测试的方法public void openFile () {System.out.println("打开文件");}//普通方法,无影响public void readFile () {System.out.println("读取文件");}@Testpublic void closeFile () {System.out.println("关闭文件");}@After//在每个标志了@Test的方法之后执行public void closeDir() {System.out.println("@After");}@AfterClass////只执行一次,标记的方法中最后执行,且为静态public static void powerOff () {System.out.println("@AfterClass");}}

?

3.静态导入

实际上使用的并不多

//静态导入属性、方法、对象,直接使用,无需前缀包名import static java.lang.Math.PI;import static java.lang.Math.abs;import static java.lang.System.out;public class Demo {public static void main(String[] args) {int r = abs(-10);double pi = PI;//Math.pow没有静态导入,所以不能直接使用powdouble area = pi * Math.pow(r, 2);out.println(r + "   " + pi + "   " + area);}}
4.自动拆箱装箱
//八种基本类型可以赋值给对应的包装类变量或者Objec变量//同样,八种包装类对象实例也可以赋值给对应的基本类型变量public class Demo {public static void main(String[] args) {Integer objI = 1;int i = objI;Object obj = 1;}}
?5.增强for循环
//方便地便利数组或者实现了Iterator接口的集合类public class Demo {public static void main(String[] args) {String[] strArr = {"ab", "cd", "ef"};for (String str : strArr) {System.out.print(str + " ");}//output : ab cd ef List<Integer> list = Arrays.asList(2, 4, 6);for (int i : list) {System.out.print(i + " ");}//output : 2 4 6 }}

?

遍历List的时候需要增删元素则使用ListIterator类, 不能在上述for循环中增删,不然运行时会出错

?

List<String> list = new LinkedList<String>();list.add("aa");list.add("bb");list.add("cc");ListIterator<String> it = list.listIterator();while (it.hasNext()) {System.out.println(it.next());it.add("ee");}System.out.println(list.size());//output : 6

?

?

注意 : 增强for循环中的变量时局部变量,值传递,并不是原集合某个元素对应的引用。

public static void main(String[] args) {String[] strArr = {"ab", "cd", "ef"};for (String str : strArr) {str = "xxx";}System.out.println(strArr[0]); //output : ab}
?6.可变参数

?

public static void main(String[] args) {show();show("aa", "bb", "cc");/*output:是null吗?false  长度: 0是null吗?false  长度: 3aa bb cc  */}//当方法中有多个参数时,可变参数要作为最后一个参数private static void show(String... strings) {System.out.println("是null吗?" + (strings==null) + "  长度: " + strings.length);for (String str : strings) {System.out.print(str + " ");}}

?

?

7.枚举类型

当需要用到一类范围内的固定常量的时候,考虑使用枚举(可以实现接口或者继承抽象类)

?

简单的枚举,及常用API使用

?

public enum Plant {FLOWER, TREE, GRASS;public static void main(String[] args) {//values 方法获得所有值Plant[] values = Plant.values();for (Plant plant : values) {System.out.println(plant);}//抛出参数异常//Plant flower = Plant.valueOf("d");//找到Plant.FLOWERPlant flower = Plant.valueOf("FLOWER");System.out.println(Plant.FLOWER == flower);//true//打印枚举值的名字System.out.println(flower.name());//FLOWER//打印某个枚举值的位置System.out.println(Plant.TREE.ordinal());//1  }}

?

?

??

带构造器和方法的枚举 (枚举类型可用于switch语句)

?

public enum Plant {FLOWER("花") {@Overridepublic void eval() {System.out.println("flower eval");}}, TREE("树") {@Overridepublic void eval() {System.out.println("tree eval");}};private String cnName;//枚举类的构造器必须为私有private Plant(String cnName) {this.cnName = cnName;}private String getCnName() {return cnName;}abstract void eval();private void operate() {switch (this) {case FLOWER:System.out.println("operate flower");break;case TREE:System.out.println("operate tree");break;default:break;}}}

?

若枚举类只含有一个值,则可作为单例使用

?

8.反射

把Java类的各个组成部分映射成一个个类,例如类的构造器、方法、成员、包等相关信息

?

定义一个Person对象

?public class Person {

private String name="defaultName";public Person() {}private Person(String name) {this.name = name;}public String getName () {return this.name;}private void showMsg (String msg, int i){System.out.println(msg + " " +i);}public void show() {System.out.println("my name is " + this.name);}}
?

?

?

反射构造器实例:

?

import java.lang.reflect.Constructor;import java.lang.reflect.InvocationTargetException;public class Demo {public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {//获得Class的三种方式//Class clazz = demo.Person.class;//Class clazz = new Person().getClass();Class clazz = Class.forName("demo.Person");//获取空参的构造函数(getConstructor只能取到公有)Constructor constructor = clazz.getConstructor(null);Object obj = constructor.newInstance();if(obj instanceof Person) {Person p = (Person)obj;p.show();}//获取带一个String类型参数的构造函数,要获得public以外的构造器要用getDeclaredConstructorConstructor constructor2 = clazz.getDeclaredConstructor(String.class);//设置取消java语言访问检查,私有的原本不能访问constructor2.setAccessible(true);Person p2 = (Person)constructor2.newInstance("newName");p2.show();}}
?

?

反射方法实例:

?

public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {Class clazz = Class.forName("demo.Person");Constructor constructor = clazz.getDeclaredConstructor(String.class);constructor.setAccessible(true);Person person = (Person)constructor.newInstance("newName");//获取公有的空参方法Method showMethod = clazz.getMethod("show", null);               //传入的第一个参数是调用该方法的实例,如果为null表示该方法是一个       //静态方法               showMethod.invoke(person, null);//获取私有的方法,类似Method showMsgMethod = clazz.getDeclaredMethod("showMsg", String.class, int.class);showMsgMethod.setAccessible(true);showMsgMethod.invoke(person, "hahah", 5);}
?

?

反射成员属性:

?

public static void main(String[] args) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchFieldException {Class clazz = Class.forName("demo.Person");Constructor constructor = clazz.getDeclaredConstructor(String.class);constructor.setAccessible(true);Person person = (Person)constructor.newInstance("newName");//Field file = clazz.getField("name");//类似获得私有的属性要用getDeclared**Field nameField = clazz.getDeclaredField("name");nameField.setAccessible(true);nameField.set(person, "reflectName");person.show();}
?

其他细节:

?

1.可以通过 clazz.newInstance()创建对应实例,原理是反射获得无参构造器再去newInstance,所以一般保证有一个空参的构造器

2.启动java程序的main方法的参数是一个字符串数组,main(String[] args),通过反射方式来调用这个main方法时。按照JDK1.5的语法,整个数组是一个参数,但是按照JDK1.4的语法,数组中的每一个元素对应一个参数,当把一个字符串数组当做参数传给invoke方法时,(为了兼容1.4)会把数组拆分成若干个单独的参数。所以再给main方法传递参数的时候,不能使用这样的代码 mainMethod.invoke(null, new String[]{"xx","yy"}), 不然会提示参数错误,因为实际上传给args的参数是 字符串"xx",而不是字符串数组。 ?解决方法 invoke(null, (Object)new String[]{"xx","yy"})

或者?invoke(null, new Object[]{new String[]{"xx","yy"}})

?

?

?

读书人网 >编程

热点推荐