java高新技术(二)

来源:互联网 发布:手机新浪博客网络异常 编辑:程序博客网 时间:2024/05/16 07:12

1.支持级联操作,以字符串的形式操作,自动作类型转换,典型运用是在将网页上传过来的字符串数据装入formbean中,反之也一样

BeanUtils.setProperty( 对象, "对象属性", "值");

直接对属性的类型进行操作,不作类型转换,当使用BeanUtils时出现类型转换错误时可以使用这个工具类

PropertyUtils.setProperty(对象, "对象属性", 值);

2.注解:就相当一个类,如何定义这个类呢,可在Eclipse中 new àAnnotation 

public @interface HemaAnnotation {“这是最简单的注解哦!”}

 

package cn.hema;import java.lang.reflect.Method;import javax.jws.soap.InitParam;//元注解:注解的注解@HemaAnnotation(annotationAttr=@MetaAnnotation("hema1"),color="red",value="abc",arrayAttr=1)public class AnnotationTest {//告诉编译器不用提示已过时,该注解保留在源文件阶段@SuppressWarnings("deprecation")@HemaAnnotation("hema2")public static void main(String[] args) throws Exception{System.runFinalizersOnExit(true);if(AnnotationTest.class.isAnnotationPresent(HemaAnnotation.class)){HemaAnnotation annotation = (HemaAnnotation)AnnotationTest.class.getAnnotation(HemaAnnotation.class);System.out.println(annotation.color());System.out.println(annotation.value());System.out.println(annotation.arrayAttr().length);System.out.println(annotation.lamp().nextLamp().name());System.out.println(annotation.annotationAttr().value());}Method mainMethod = AnnotationTest.class.getMethod("main", String[].class);HemaAnnotation annotation2 = (HemaAnnotation)mainMethod.getAnnotation(HemaAnnotation.class);System.out.println(annotation2.value());}//在源代码上加上这个注解可提示此方法已过时@Deprecatedpublic static void sayHello(){System.out.println("hi,hema3");}}


自己定义的注解类:

package cn.hema;//设置该注解保留在什么阶段,RetentionPolicy是个枚举,有三个取值,RUNTIME保留在运行时,SOURCE保留在源代码阶段,CLASS保留在class阶段,默认在class阶段@Retention(RetentionPolicy.RUNTIME)//设置该注解运用在什么对象上,ElementType.TYPE 是java中的类型,class是Type的子类@Target({ElementType.METHOD,ElementType.TYPE})public @interface HemaAnnotation {//设置属性的默认值String color() default "blue";//没有默认则为必填项String value();int[] arrayAttr() default {3,4,4};//属性是枚举类型的EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;//属性是注解类型的MetaAnnotation annotationAttr() default @MetaAnnotation("hema coming");}

 

总结:注解相当于一种标记,在程序中加了注解就等于为程序打上了一个标记,没有加等于没有某种标记,以后,javac编译器,开发工具和其它程序可以用反射来了解你的类及各种元素上有无何种标记,看你有什么标记,就去干相应的事。标记可以加在包,类,字段,方法,方法的参数以及局部变量上。在web开发中,就用到了注解来设置实体类和数据库的对应关系,非常好用!