3. 自定义注解:
当注解中的属性名为value时,在对其赋值时可以不指定属性的名称而直接写上属性值即可;
除了value以外的其他值都需要使用name=value这种赋值方式,即明确指定给谁赋值。
4. 当我们使用@interface关键字定义一个注解时,该注解隐含地继承了java.lang.annotation.Annotation接口;
如果我们定义了一个接口,并且让该接口继承自Annotation,那么我们所定义的接口依然还是接口而不是注解;Annotation本身是接口而不是注解。可以与Enum类比。
@Retention(RetentionPolicy.CLASS)//只有为RUNTIME时 if有用 public @interface MyAnnotation { String hello() default "shengsiyuan"; String world(); }
@MyAnnotation(hello = "beijing", world = "shanghai") public class MyTest { @MyAnnotation(hello = "tianjin", world = "shangdi") @Deprecated @SuppressWarnings("unchecked") public void output() { System.out.println("output something!"); } }
public static void main(String[] args) throws Exception { MyTest myTest = new MyTest(); Class<MyTest> c = MyTest.class; Method method = c.getMethod("output", new Class[]{}); if(method.isAnnotationPresent(MyAnnotation.class)) { method.invoke(myTest, new Object[]{}); MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class); String hello = myAnnotation.hello(); String world = myAnnotation.world(); System.out.println(hello + ", " + world); } Annotation[] annotations = method.getAnnotations(); for(Annotation annotation : annotations) { System.out.println(annotation.annotationType().getName()); }
@Target(ElementType.METHOD) public @interface MyTarget { String value(); }
5. 配置Junit:
右键项目-buildpath-configurebuildpath-libraries-AddLibraries-JUnit
Junit3所有方法都以test命名,public
public class Test extends TestCase { public void testadd() { for(int i=0;i<1000;i++){ for (int j = 0; j < 10000; j++) { int b=i+j; } } } }7. JUnit4的执行的一般流程:(利用了反射和注解)
e) 如果该方法返回true,那么调用method.invoke()方法去执行该方法,否则不执行。
8. 单元测试不是为了证明你是对的,而是证明你没有错误。
9. Writing Secure Code(编写安全的代码):Input is evil。
11. Java中的异常分为两大类:a) Checked exception (非 Runtime Exception)
b) Unchecked exception(Runtime Exception)
却调用了它的某个方法。这时就会出现该异常。
19 所谓自定义异常,通常就是定义了一个继承自Exception类的子类,那么这个类就是一个自定义异常类。通常情况下,我们都会直接继承自Exception类,一般不会继承某个运行时的异常类。
public class ExceptionTest2 extends Exception { public ExceptionTest2(String mString) { super(mString); } }
public static void method(String str) throws Exception { if (str ==null) { throw new ExceptionTest2("字符串不能为空"); } else { System.out.println(str); } } public static void main(String[] args) throws Exception { method(null); }
20我们可以使用多个catch块来捕获异常,这时需要将父类型的catch块放到子类型的catch块之后,这样才能保证后续的catch可能被执行,否则子类型的catch将永远无法到达,Java编译器会报编译错误;如果多个catch块的异常类型是独立的(MyException, MyException2), 那么谁前谁后都是可以的。
public class ExceptionTest3 extends ExceptionTest2 { public ExceptionTest3(String str) { super(str); } }
catch (ExceptionTest3 e) { System.out.println(e.getMessage()); } catch (ExceptionTest2 e) { System.out.println(e.getMessage()); }
21如果try块中存在return语句,那么首先也需要将finally块中的代码执行完毕,然后方法再返回。
22如果try块中存在System.exit(0)语句,那么就不会执行finally块中的代码,因为System.exit(0)会终止当前运行的Java虚拟机,程序会在虚拟机终止前结束执行。
参数0表示正常退出
非0参数表示异常退出