java getannotation(),Java Method类 getAnnotation()用法及代码示例

Method类的java.lang.reflect.Method.getAnnotation(Class 注记类)方法返回指定类型的方法对象的注解(如果存在),则将其作为参数传递给参数,否则为null。这是获取Method对象注释的重要方法。

用法:

public T getAnnotation(Class annotationClass)

参数:此方法采用强制性参数注释类,它是注释类型的Class对象。

返回值:如果此元素上存在指定的注释类型,则此方法返回该方法的注释,否则返回null。

异常:如果给定的注释类为null,则此方法引发NullPointerException

以下示例程序旨在说明Method类的getAnnotation(Class注解类)方法:

范例1:此程序将打印指定注释类型的方法注释,该注释作为参数提供给表示GFG类的getCustomAnnotation()方法的“方法对象”的getAnnotation()。

在该示例中,使用单个类,并且该类包含两种方法,它们是主要方法和带有注释的方法。

// Program Demonstrate getAnnotation(Class annotationClass) method

// of Method Class.

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.reflect.Method;

// create a custom Annotation

@Retention(RetentionPolicy.RUNTIME)

@interface Annotation {

// This annotation has two attributes.

public String key();

public String value();

}

// create the Main Class

public class GFG {

// call Annotation for method and pass values for annotation

@Annotation(key = "AvengersLeader", value = "CaptainAmerica")

public static void getCustomAnnotation()

{

try {

// create class object for class name GFG

Class c = GFG.class;

// get method name getCustomAnnotation as Method object

Method[] methods = c.getMethods();

Method method = null;

for (Method m:methods) {

if (m.getName().equals("getCustomAnnotation"))

method = m;

}

// get Annotation of Method object m by passing

// Annotation class object as parameter

Annotation anno = method.getAnnotation(Annotation.class);

// print Annotation Details

System.out.println("Annotation for Method Object"

+ " having name:" + method.getName());

System.out.println("Key Attribute of Annotation:"

+ anno.key());

System.out.println("Value Attribute of Annotation:"

+ anno.value());

}

catch (Exception e) {

e.printStackTrace();

}

}

// create main method

public static void main(String args[])

{

getCustomAnnotation();

}

}

输出:

Annotation for Method Object having name:getCustomAnnotation

Key Attribute of Annotation:AvengersLeader

Value Attribute of Annotation:CaptainAmerica

范例2:此程序将打印指定注释类型的方法注释,该注释作为参数提供给表示GFG类的getCustomAnnotation()方法的“方法对象”的getAnnotation()。

在此示例中,使用了两个类。一个类包含main方法,该方法创建方法对象并应用getAnnotation()方法,而另一个类包含带有某些注释的方法。

// Program Demonstrate getAnnotation(Class annotationClass) method

// of Method Class.

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.reflect.Method;

public class GFG {

public static void main(String[] args)

{

// get array Method objects

Method[] methods = GFGDemoClass.class.getMethods();

// get Annotation

SelfCreatedAnnotation annotation = methods[0]

.getAnnotation(

SelfCreatedAnnotation

.class);

// Print annotation attribute

System.out.println("key:" + annotation.key());

System.out.println("value:" + annotation.value());

}

}

// Another class on which we want to apply the annotation

class GFGDemoClass {

private String field;

// create annotation

@SelfCreatedAnnotation(key = "getField",

value = "getting field attribute")

public String

getField()

{

return field;

}

}

// create custom annotation having two values

@Retention(RetentionPolicy.RUNTIME)

@interface SelfCreatedAnnotation {

public String key();

public String value();

}

输出:

key:getField

value:getting field attribute

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JAVA高级特性 1.静态导入:先举个离例子 。 import java.lang.Integer.parseInt; public class StaticImport { int x = parseInt("123"); System.out.println(x); } 这样的程序如果不在IDE 工具中输入,是很难看出这个程序代码会出现问题,可它偏偏就出问题了,这是为什么呢?因为程序里面有个静态方法,如果导入import static java.lang.Integer.parseInt;这样的程序就可以运行了。 2.可变参数与for循环增强 这个是一般的用法: public static void loop(String[] args){ for(int i=0;i<args.length;i++) { System.out.println(args[i]); } } 这个是JDK 增加的新特性的用法! public static void loop(int x,int... args ) { //这里的参数一定要以这样的形式输入 for(int i:args) { System.out.println(i); } } 3.枚举 写枚举技巧: 1. enum Gender{MALE,FEMALE,BOTH} 2. enum Gender{MALE,FEMALE,BOTH;public abstract getTitle();} 3.enum Gender{MALE{},FEMALE{},BOTH{};public abstract getTitle();} 4.填充各个{}中的getTitle方法。 下面是个红绿黄灯的例子: public enum TrafficLamp { RED(30){ public TrafficLamp next() { return GREEN; } }, GREEN(50){ public TrafficLamp next() { return YELLOW; } }, YELLOW(5){ public TrafficLamp next() { return RED; } }; public abstract TrafficLamp next(); private int time; private TrafficLamp(int time) { this.time = time; } 4.反射. 这个知识点,真是费了我好大劲才理解。当真正理解了,其实也就不难了。先举例子来理解什么是反射。 先建这样的一个,带会下面有个里面有反射成员变量的方法的! public class ReflectPoint { private int x; public int y; public ReflectPoint(int x, int y) { super(); this.x = x; this.y = y; } } public class Test{ String obj = (String)Class.forName("java.lang.String").newInstance(); 这是制造另一个章:Class.forName("java.lang.Integer") --------------------- 讲Constructor://构造方法 Constructor constructors[] = Class.forName("java.lang.String").getConstructors(); Constructor constructor = Class.forName("java.lang.String").getConstructor(StringBuffer.class); String str = (String)constructor.newInstance(new StringBuffer("abc")); System.out.println(str); class.newInstance()内部其实就是在用默认的构造方法 ----------------------- 讲Method //方法 Method charAt = Class.forName("java.lang.String").getMethod("charAt", int.class); System.out.println(charAt.invoke(str, 1)); ------------------------- 讲Field //成员变量 ReflectPoint point = new ReflectPoint(1,7); Field y = Class.forName("cn.itcast.corejava.ReflectPoint").getDeclaredField("y"); y.setAccessible(true); System.out.println(y.get(point)); Field x = Class.forName("cn.itcast.corejava.ReflectPoint").getDeclaredField("x"); x.setAccessible(true); System.out.println(x.get(point)); } 在这里我们运行的时候可以看出,ReflectPoint里面的x和y 都可以打印出来了! 学习心得:先从这四个知识点来看,张老师的确很让人敬佩!以上的一些程序代码均为张老师课堂即兴发挥所写,也可以看出,张老师对JAVA特性的深刻理解能力!现在说说我对这些程序代码的理解,说实话,才开始听张老师讲的时候,我感觉很模糊的,但是当我真正理解了之后,觉得这些程序写的真是太好了。象以后我门在学习JAVA 的时候,一定要对每个知识点要慢慢的消化吃透,切不能走马观花。一个知识点必须要反复的动手练习,不然很难理解其中的奥秘所在的! 5.在JAVA的程序中,我经常性的看到字符前面有@这种标志的符号.这个就叫做注解! 下面是使用 @SuppressWarnings 来取消 deprecation 警告的一个例子: public class Test { @Deprecated //在eclipse下运行的时候,方法名上会加一横线 public static void sayHello() { } } public class Test2 { @SuppressWarnings("deprecation") //在mian方法内调用一个没有定义的方法时,运行的时候将会出现这一注解! public static void main(String [] args) { Test.sayHello(); } } @SuppressWarnings 批注允许您选择性地取消特定代码段(即,或方法)中的警告。其中的想法是当您看到警告时,您将调查它,如果您确定它不是问题,您就可以添加一个 @SuppressWarnings 批注,以使您不会再看到警告。虽然它听起来似乎会屏蔽潜在的错误,但实际上它将提高代码安全性,因为它将防止您对警告无动于衷 — 您看到的每一个警告都将值得注意。 由如下代码引出@Override的讲解: User中的方法: public boolean equals(User other) { return name.equals(other.name); } 下面的代码执行时将有问题: User user1 = new User(); User user2 = new User(); user1.setName("abc"); user2.setName("abc"); System.out.println(user1.equals(user2)); HashSet set = new HashSet(); set.add(user1); set.add(user2); System.out.println(set.size());//期望结果为1,但实际为2 这时候在User的equals方法上加上@Override,发现了问题。 再看看这个代码:一看就知道有问题, 这里 就有个很好的解决办法,在写public @interface MyAnnotation {}这样的的时候,下面的代码上的错误提示就是结束的! public class dsds { public static void main(String[] args) throws Exception{ // TODO Auto-generated method stub System.out.println(User.class.isAnnotationPresent(MyAnnotation.class) ); System.out.println( User.class.getAnnotation(MyAnnotation.class) ); } } 运行的结果为:false null 下面演示了一下@Target和@Retention import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.TYPE}) //用于构造方法 @Retention(RetentionPolicy.RUNTIME) //在运行是加载Annotation到JVM中 public @interface MyAnnotation { public String value() default "yellow"; public int[] array() default {1,2}; public MetaAnnotation annotation() ; } 注解最主要的就是这么多,其实注解真正的,我们都很少留心的,但是有的注解会给你在写程序和查找错误的时,会有很大的帮助的! 6.泛型: 1、泛型的型参数只能是型(包括自定义),不能是简单型。 2、同一种泛型可以对应多个版本(因为参数型是不确定的),不同版本的泛型实例是不兼容的。 3、泛型的型参数可以有多个。 4、泛型的参数型可以使用extends语句,例如<T extends superclass>。习惯上成为“有界型”。 5、泛型的参数型还可以是通配符型。例如Class<?> classType = Class.forName(java.lang.String); 例子: a..使用?通配符可以引用其他各种参数化的型,但不能调用与参数化有关的方法; Collection<?> c = new Vector<String>(); c.add("abc");//报错 c.size();//正确 所以,?通配符定义的变量主要用作引用,调用与参数化无关的方法,如果要调用与参数化相关的方法,那么必须在使用?通配符引用之前调用,否则就与java 5提供泛型的目的背道而驰了。 b..向下限定通配符: 正确:Vector<? extends Number> x = new Vector<Integer>(); 错误:Vector<? extends Number> x = new Vector<String>(); 向上限定通配符: 正确:Vector<? super Integer> x = new Vector<Number>(); 错误:Vector<? super Integer> x = new Vector<Byte>(); 7.代理 这里就直接先应用张老师写的代码然后再讲清其原理吧! package cn.itcast.corejava; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Collection; import java.util.Vector; public class ProxyTest { public static void main(String[] args) { System.out.println(Integer.class.getClassLoader()); //System.out.println(ProxyTest.class.getClassLoader().getParent().getClass().getName()); System.out.println(ProxyTest.class.getClassLoader().getClass().getName()); //test1(); //test2(); } private static void test3() { Vector v = new Vector(); class MyInvocationHandler implements InvocationHandler { Collection target = null; public Collection bind(Collection target) { this.target = target; Collection proxy1 = (Collection)Proxy.newProxyInstance( ProxyTest.class.getClassLoader(), new Class[]{Collection.class} , this); return proxy1; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin " + method.getName()); Object retval = method.invoke(target, args); System.out.println("end" + method.getName()); return retval; } } MyInvocationHandler handler = new MyInvocationHandler(); Collection proxy1 = handler.bind(v); System.out.println(proxy1.getClass().getName()); proxy1.add("abc"); proxy1.add("xyz"); System.out.println(proxy1.size()); } private static void test2() { Vector v = new Vector(); class MyInvocationHandler implements InvocationHandler { Collection target = null; public MyInvocationHandler(){} public MyInvocationHandler(Collection target){this.target = target;} public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin " + method.getName()); Object retval = method.invoke(target, args); System.out.println("end" + method.getName()); return retval; } } Collection proxy1 = (Collection)Proxy.newProxyInstance( ProxyTest.class.getClassLoader(), new Class[]{Collection.class} , new MyInvocationHandler(v)); System.out.println(proxy1.getClass().getName()); proxy1.add("abc"); proxy1.add("xyz"); System.out.println(proxy1.size()); } private static void test1() { Collection proxy = (Collection)Proxy.newProxyInstance( ProxyTest.class.getClassLoader(),//first parameter new Class[]{Collection.class} , //second parameter new InvocationHandler(){ //third parameter Vector target = new Vector(); public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // TODO Auto-generated method stub System.out.println("begin " + method.getName()); Object retval = method.invoke(target, args); System.out.println("end" + method.getName()); return retval; } } ); System.out.println(proxy.getClass().getName()); proxy.add("abc"); proxy.add("xyz"); System.out.println(proxy.size()); } } 以下是Proxy的API文档: public class Proxyextends extends Object implements Serializable Proxy provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods. To create a proxy for some interface Foo: InvocationHandler handler = new MyInvocationHandler(...); Class proxyClass = Proxy.getProxyClass( Foo.class.getClassLoader(), new Class[] { Foo.class }); Foo f = (Foo) proxyClass. getConstructor(new Class[] { InvocationHandler.class }). newInstance(new Object[] { handler }); or more simply: Foo f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(), new Class[] { Foo.class }, handler);从以上的程序中在方法中定义参数的时候总是三个参数,可这三个参数有分别代表什么意思呢!?现在以我自己个人的理解,比如我是买家,我要买本书,可是现在我有事,是不是需要别人代我买呢?那带我买的人是不是一定要到卖书的地方买呢?所以着中间产生了三个实体.说白了就是一种代理机制.需要三方一起运行! 代理其实很好理解的,而且会用固定的语法格式,很快会掌握这一原理的!
全部是txt格式的,容量小,以下内容为其中之一: 5.0新特性: 泛型: 泛型的形式: <E> <E extends 型> <E extends Numner&comparator> 名&接口,表示E继承Numner实现comparator接口 <?> 泛型通配符表示任意型,仅用于传参 <? extends 型> 表示这个型可以是该或者该的子。 <? super 型> 表示这个型可以是该或者该的父。 泛型的优点: 指定泛型后,取出数据时不需要进行强制型转换,可以直接赋值给相应型。 可以限定集合中的元素型,保证集合中的元素是按照要求放入的。 可以增强多态(继承多个接口而无需写继承)。 保证参数有效。 泛型的局限性: 不能实例化泛型 T t = new T(); //error 数组不可用泛型限定 List<String>[] list = new List<String>[10]; //错误 E[] a = new E[10]; //错误 的静态变量不能声明为的泛型型 public class GenClass<T> { private static T t; //编译错误 } 静态方法可以是泛型方法(在修饰符和返回值之间写泛型),但是不可以使用的泛型。 static void copyArrayToList(Object[] os,List<T> ls){ //错误,T为的泛型 } static <E> void copyArrayToList(E[] os,List<E> ls){ //泛型方法,正确的 } 泛型不能使用简单型 GenList<int> nList = new GenList<int>(); //编译错误 泛型不能是异常,也就是该泛型不能继承自Throwable以及其子 public class MyExpection<T> extends Exception{ } //编译错误 可以抛出(throws)泛型,但catch的参数不能是泛型。 注意: 编译时型的泛型和运行时型的泛型一定要一致,没有多态。 支持泛型的集合,只能存放指定的型,或者是指定型的子型。 注释(元数据): 描述代码代码,作用是规范编译器的语法。 三种内置注释: @Deprecated 所标注的程序元素是不推荐使用的 @Override 检查是否为合法的覆盖父的方法 @SuppressWarnings 注释或方法,忽略其中的某些型的警告信息 注释的三种型: 标记注释:不需要任何参数 @Override @Deprecated 单值注释:有一个值的注释 @注释名(值名=值) 值名一般为value,可以省略的,直接写值就可以 值的型是有限制的,只能是以下几种: 8种基本数据型 String Class Enum Annotation 以及他们的数组 多值注释:每个值之间用逗号隔开 四种元注释:java.lang.annotation中的 元注释:注释注释的注释,用来限定注释的特征 @Terget 用来限定某个注释的使用范围,可以对什么元素进行注释 @Retention 用来描述注释的有效范围 @Inherited 用来描述某注释是否有继承性 @Documented 用来限定注释的信息是否能够进行文档化 自定义注释: 在自定义注释时,要用元注释来进行描述。 如: import java.lang.annotation.*; @Target({ElementType.METHOD}) @Inherited @Retention(RetentionPolicy.RUNTIME) @Documented public @interface InProgress { String author(); //定义属性 String limited(); } 解析注释:利用反射 1、Class.forName() 2、getMethod 3、判断是否有注释 4、getAnnotation 并发线程: 三个多线程包: java.util.concurrent 包含了常用的多线程工具,是新的多线程工具的主体。 java.util.concurrent.atomic 包含了不用加锁情况下就能改变值的原子变量。 java.util.concurrent.locks 包含锁定的工具。 Executor接口: 替代了Thread,他可以创建定量的、动态的以及周期性的线程池。 ExecutorService接口: 线程池,用来存放线程来节省创建和销毁资源的消耗。 Callable和Future接口: Callable是似于Runnable的接口,实现Callable接口的和实现Runnable的都是可被其它线程执行的任务。Callable和Runnable有几点不同: Callable规定的方法是call(),而Runnable规定的方法是run(). Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。 call()方法可抛出异常,而run()方法是不能抛出异常的。 运行Callable任务可拿到一个Future对象,通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值