`

lang.reflect->java.lang.reflect.Method

阅读更多
java中反射使用几率最多的就是方法的反射。
功能支持的类库:java.lang.reflect.Method

提供的功能包括:
1、获取方法上的注解信息。(getAnnotations、getDeclaredAnnotations)
2、获取方式上的某个注解信息Annotation。(getAnnotation(Type.class))
3、获取方法上的类型参数Type。(getTypeParameters)
4、获取方式声明的异常类型Class[]。(getExceptionTypes)
5、获取方式上的参数注解。(getParameterAnnotations)
6、获取方法返回的数据类型Class。(getReturnType)
7、获取方法方法的参数类型Class[](getParameterTypes)
8、执行某个方法(invoke(Object obj, Object... args))

以上功能是使用最频率最多的方法,请结合案例仔细体会之!

测试案例:

package array;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,ElementType.TYPE,ElementType.CONSTRUCTOR })
@interface Note {
    public boolean require() default true;
    public String note() default "";
}

@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,ElementType.TYPE,ElementType.CONSTRUCTOR })
@interface Type {
    public boolean require() default true;
    public String type() default "";
}

@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER,ElementType.TYPE,ElementType.CONSTRUCTOR })
@interface Face {
    public boolean require() default true;
    public String face() default "";
}

interface IB{
    @Face(face="method->face")
    public boolean loginUser(String username,String password) throws RuntimeException,SQLException;
}

@Note(note= "calss->B",require = false)
public class B implements IB{
    @Note(note="field->note")
    @Type(type="field->type")
    public List<String> note = Arrays.asList("defaultValue");
    
    @Note(note="CONSTRUCTOR->B")
    public <T> B(@Note(note = "p->note") @Type(type = "p->type") String note,String note2){
    }
    
    @Note(note = "method ->login()",require = true)
    public void login(@Note(note = "p->username") String username, @Note(note = "p->password")String password) {
    }
    
    @Note(note = "method ->login()",require = true)
    @Type(type = "p->type->username",require = false) 
    public boolean  loginUser(@Note(note = "p->note->username") @Type(type = "p->type->username") String username, @Type(type = "p->password")String password)
    throws RuntimeException,SQLException{
      return true;
    }

    public <N,P> N getUserInfo(){
	return null;
    }
    public List<String> getNote() {
        return note;
    }

    public void setNote(List<String> note) {
        this.note = note;
    }
    
}

package array;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.lang.reflect.TypeVariable;
import java.util.Arrays;
/**
 * 测试方法反射方法
 * @author create by [url=xinchunwang@aliyun.com]新春.王[/url] <br> 
 *
 */
public class MethodReflect {
    public static void main(String[] args) throws Exception {
	// 获取B.class 的loginUser方法 注意参数:("loginUser", String.class,String.class)
	Method loginMethod = B.class.getMethod("loginUser", String.class, String.class);
	
	//NOTE:方法上声明的注解是无法继承的
	//获取方法上的所有注解
	Annotation[] methodAnno = loginMethod.getAnnotations();
	for(Annotation item : methodAnno) {
	    if(item instanceof Note){
		Note note = (Note)item;
		System.out.println(note);
	    }else if(item instanceof Type){
		Type type = (Type)item;
		System.out.println(type);
	    }else{
		System.out.println(item);
	    }
	}
	//获取直接在方法上的注解
	Annotation[] declareMethodAnno =loginMethod.getDeclaredAnnotations();
	for(Annotation item : declareMethodAnno) {
	    if(item instanceof Note) {
		Note note = (Note)item;
		System.out.println(note);
	    }else if(item instanceof Type){
		Type type = (Type)item;
		System.out.println(type);
	    }else {
		System.out.println(item);
	    }
	}
	System.out.println("----------------------------------");
	
	//获取方法上某个类型的注解
	Type type = (Type)loginMethod.getAnnotation(Type.class);
	System.out.println(type);
	//如果方法上没有此注解,直接返回null
	Face face = (Face)loginMethod.getAnnotation(Face.class);
	System.out.println(face);
	System.out.println(loginMethod.getDefaultValue());
	
	System.out.println("-----------------------------------------");
	//获取方法返回的类型参数列表
	Method getUserInfo = B.class.getMethod("getUserInfo");
	TypeVariable[] typeVar = getUserInfo.getTypeParameters();
	for(TypeVariable item :typeVar){
	    System.out.println(item.getName());
	    java.lang.reflect.Type[] bounds =  item.getBounds();//参数类型的 上下边界
	    System.out.println(bounds);
	}
	System.out.println(Arrays.toString(typeVar));
	
	System.out.println("-----------------------------------------");
	//获取方法返回的异常列表
	Class[] exceptions = loginMethod.getExceptionTypes();
	System.out.println(Arrays.toString(exceptions));
	
	System.out.println("-----------------------------------------");
	//获取参数的类型
	Class[] parameterTypes = loginMethod.getParameterTypes();
	System.out.println(Arrays.toString(parameterTypes));
	
	System.out.println("-----------------------------------------");
	//获取参数上的注解
	Annotation[][] parameterAnno = loginMethod.getParameterAnnotations();
	for(Annotation[] item : parameterAnno){
	    System.out.println(Arrays.toString(item));
	}
	
	System.out.println("-----------------------------------------");
	//获取返回的类型
	Class returnType = loginMethod.getReturnType();
	System.out.println(returnType);
	
	B b = new B("","");
	//执行某个方法
	boolean result =(Boolean)loginMethod.invoke(b, "","");
	System.out.println(result);
    }
}



测试输出:
@array.Note(require=true, note=method ->login())
@array.Type(require=false, type=p->type->username)
@array.Note(require=true, note=method ->login())
@array.Type(require=false, type=p->type->username)
----------------------------------
@array.Type(require=false, type=p->type->username)
null
null
-----------------------------------------
N
[Ljava.lang.reflect.Type;@5a8a0d5d
P
[Ljava.lang.reflect.Type;@1d73831b
[N, P]
-----------------------------------------
[class java.lang.RuntimeException, class java.sql.SQLException]
-----------------------------------------
[class java.lang.String, class java.lang.String]
-----------------------------------------
[@array.Note(require=true, note=p->note->username), @array.Type(require=true, type=p->type->username)]
[@array.Type(require=true, type=p->password)]
-----------------------------------------
boolean
true
分享到:
评论

相关推荐

    server frame base on c.rar

    java.lang.NullPointerException ... at java.lang.reflect.Method.invoke(Method.java:498) at org.apache.tomcat.websocket.pojo.PojoMessageHandlerWholeBase.onMessage(PojoMessageHandlerWholeBase.java:80)

    java Reflection 反射机制 反编译

    import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectionTest { public static void main(String[] args) { Class c = null; try { c = Class.forName("java.lang....

    java 反射例子 代码

    java.lang.reflect.Constructor; java.lang.reflect.Field; java.lang.reflect.Method; java.lang.reflect.Modifier;

    android 奔溃日志收集 发送邮件到邮箱

    集成邮件工具类,用于发送某个应用的奔溃日志信息到邮箱。...at java.lang.reflect.Method.invoke(Native Method) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:10

    ExcelExportUtils.java

    import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util....

    javassist3.19GA.jar

    用以执行和JDK反射API中java.lang.Class,,java.lang.reflect.Method,, java.lang.reflect.Method .Field相同的操作。这些类可以使你在目标类被加载前,轻松的获得它的结构,函数,以及属性。此外,不仅仅是在功能...

    org.eclipse.jdt.core_3.5.2.v_981_R35x

    at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable....

    java反射(reflect)

    java反射(reflect)

    aop面向切面需要的jar包

    Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.reflect.ReflectionWorld$ReflectionWorldException at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.Access...

    spring aop 实现源代码--xml and annotation(带lib包)

    import java.lang.reflect.Method; 4. 5. import org.springframework.aop.framework.MethodBeforeAdvice; 6. 7. public class LogBeforeAdvice implements MethodAdvice { 8. public void before(Method ...

    jaxen.jar和dom4j.jar

    at java.lang.reflect.Method.invoke(Unknown Source) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44) at org.junit.internal.runners.model.ReflectiveCallable.run...

    信息: Deploying web application directory lx01

    at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414) 2010-11-11 ...

    Java高级程序设计实战教程第三章-Java反射机制.pptx

    //类的成员变量 java.lang.reflect.Method;//类的方法 java.lang.reflect.Modifier;//访问权限 Java高级程序设计实战教程第三章-Java反射机制全文共15页,当前为第6页。 3.2.4 使用反射机制的步骤 导入Jjava.lang....

    JavaSE-6.0-英文手册(2008/11/30_FullUpdate)

    java.lang.reflect java.math java.net java.nio java.nio.channels java.nio.channels.spi java.nio.charset java.nio.charset.spi java.rmi java.rmi.activation java.rmi.dgc java.rmi.registry java...

    COS——R.log

    at java.lang.reflect.Method.invoke(Method.java:585) at org.apache.axis.providers.java.RPCProvider.invokeMethod(RPCProvider.java:397) at org.apache.axis.providers.java.RPCProvider.processMessage...

    c3p0工具包(jdbc)

    import java.lang.reflect.Method; import java.lang.reflect.Proxy; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet....

    java反射机制

    import java.lang.reflect.Method; public class DumpMethods { public static void main(String args[]) throws Exception { // 加载并初始化命令行参数指定的类 Class&lt;?&gt; classType = Class.forName(args[0])...

    HIbernate4.3.6整合c3p0所需jar

    at java.lang.reflect.Method.invoke(Method.java:597) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45) at org.junit.internal.runners.model.ReflectiveCallable....

    struts2驱动包

    at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) Caused by: java...

    richfaces_erro

    java.lang.reflect.InvocationTargetException at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance...

Global site tag (gtag.js) - Google Analytics