java 反射功能强大,也是很多基础框架的核心技术。结合jdk1.5 的注解功能java反射技术再很多项目中成了必备的技术。
本例子展现了java.lang.reflect.Field类的使用方法以及方法的含义。
从功能上划分Field反射功能包含:
1、与注解相关方法。声明在 AnnotatedElement 接口中:
public interface AnnotatedElement {
/**
判断当前Element 是否有annotationClass注解信息
*/
boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);
/**
返回当前element 对象的annotationClass 注解信息 没有annotationClass 注解信息会抛出异常
*/
<T extends Annotation> T getAnnotation(Class<T> annotationClass);
/**
返回当前Element 对象的所有注解信息
*/
Annotation[] getAnnotations();
/**
返回直接声明在当前Element对象的所有注解信息(一般在Method中使用)
*/
Annotation[] getDeclaredAnnotations();
}
2、Field 值的设置和获取信息。
public Object get(Object obj){...}
public boolean getBoolean(Object obj){...}
public void set(Object obj, Object value){...}
详细请参考jdk代码。(略)
3、Field 元信息。(名称、类型、泛型参数等)
public String getName() //返回field声明的名字
public Class<?> getType() //返回field声明的类型
public Type getGenericType()// 包含泛型的field声明的类型
public int getModifiers() //返回public、final 、static 等修饰符
综合例子:
@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 note() default "";
}
@Note(note= "calss->B",require = false)
class B {
@Note(note="field->note")
@Type(note="field->type")
public List<String> note = Arrays.asList("defaultValue");
@Note(note="CONSTRUCTOR->B")
public <T> B(@Note(note = "p->note") @Type(note = "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)
public boolean loginUser(@Note(note = "p->username") String username, @Note(note = "p->password")String password) {
return true;
}
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.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 字段反射
* @author xinchun.wang
*
*/
public class FieldReflect {
public static void main(String[] args) throws Exception {
//生成一个真实的B对象
B b = new B("testNote", "note2");
//获取B.class 的loginUser方法 注意参数:("loginUser", String.class,String.class)
Method loginMethod = B.class.getMethod("loginUser", String.class,String.class);
//获取声明loginMethod 所在Class对象 即:B.class
Class<?> type = (Class<?>) loginMethod.getDeclaringClass();
System.out.println("----------------begin getDeclaringClass------------------------");
System.out.println(type);
System.out.println(B.class);
System.out.println(type.equals(B.class)); //true
System.out.println(type == B.class); //true
System.out.println("----------------end getDeclaringClass------------------------");
System.out.println("----------------begin getField------------------------");
//获取一个成员变量 (field 必须为public)
Field field = B.class.getField("note");
System.out.println(field.getName()); //获取声明的note变量
System.out.println(field.isAccessible()); // false :默认 不优化处理。返回是否可以优化处理 (注意含义请阅读api)
field.setAccessible(true);
System.out.println("----------------end getField------------------------");
//获取b对象的常量
@SuppressWarnings("unchecked")
List<String> objField = (List<String>)field.get(b);
System.out.println(objField);
List<String> list = new ArrayList<String>();
list.add("goodBoy");
field.set(b, list);
objField = (List<String>)field.get(b);
System.out.println(objField);
//获取字段的所有注解信息
Annotation[] fieldAnno = field.getAnnotations();
for (Annotation anno : fieldAnno) {
if (anno instanceof Note) {
System.out.println(((Note) anno).note());
}
}
//获取某一个类型的注解
Note note = field.getAnnotation(Note.class);
System.out.println(note.note());
//获取包含泛型信息的字段类型信息
java.lang.reflect.Type refType = field.getGenericType();
System.out.println(refType);
//获取字段的参数类型
System.out.println("***************");
if(refType instanceof ParameterizedType){
ParameterizedType pType = (ParameterizedType)refType;
java.lang.reflect.Type[] types = pType.getActualTypeArguments();
System.out.println(Arrays.toString(types));
}
System.out.println("***************");
//获取字段的类型信息
System.out.println(field.getType());
//获取直接在字段上声明的注解信息
Annotation[] anno = field.getDeclaredAnnotations();
for(Annotation item :anno){
System.out.println( item);
}
}
}
运行结果:
----------------begin getDeclaringClass------------------------
class array.B
class array.B
true
true
----------------end getDeclaringClass------------------------
----------------begin getField------------------------
note
false
----------------end getField------------------------
[defaultValue]
[goodBoy]
field->note
field->note
java.util.List<java.lang.String>
***************
[class java.lang.String]
***************
interface java.util.List
@array.Note(require=true, note=field->note)
@array.Type(require=true, type=field->type)
分享到:
相关推荐
java.lang.reflect.Constructor; java.lang.reflect.Field; java.lang.reflect.Method; java.lang.reflect.Modifier;
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; public class ReflectionTest { public static void main(String[] args) { Class c = null; try { ...
java反射(reflect)
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; ...
用以执行和JDK反射API中java.lang.Class,,java.lang.reflect.Method,, java.lang.reflect.Method .Field相同的操作。这些类可以使你在目标类被加载前,轻松的获得它的结构,函数,以及属性。此外,不仅仅是在功能...
//构造方法 java.lang.reflect.Field; //类的成员变量 java.lang.reflect.Method;//类的方法 java.lang.reflect.Modifier;//访问权限 Java高级程序设计实战教程第三章-Java反射机制全文共15页,当前为第6页。 3.2.4 ...
我看了几个文章,主要是接受配对广播,然后设置pin,实现配对,但是网上的大部分手机是不可以的,Android....import java.lang.reflect.Field; import android.bluetooth.BluetoothAdapter; import android.bluetooth
例如Class<?> classType = Class.forName(java.lang.String); 例子: a..使用?通配符可以引用其他各种参数化的类型,但不能调用与参数化有关的方法; Collection<?> c = new Vector<String>(); c.add("abc");//报错...
本文实例讲述了Android编程实现获取系统内存、CPU使用率及状态栏高度的方法。分享给大家供大家参考,具体如下: DeviceInfoManage类用于获取系统的内存,CPU的信息,...import java.lang.reflect.Field; import java.ut
1.Configuration.xml 是 mybatis 用来建立 sessionFactory 用的,里面主要包含了数据库连接相关东西,还有 java 类所对应的别名,比如 <typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/> 这个别名...
import java.lang.reflect.InvocationTargetException; /** * A demo PDF Viewer application. */ public class PDFViewer extends JFrame implements KeyListener, TreeSelectionListener, PageChangeListener...
包含以下java源文件: com.google.gson.DefaultDateTypeAdapter.class com.google.gson.ExclusionStrategy.class com.google.gson.FieldAttributes.class com.google.gson.FieldNamingPolicy.class ...
Java反射技术的核心在于java.lang.reflect包,它提供了一系列类和接口,用于在运行时获取关于类和对象的信息,并进行相应的操作。主要的类和接口包括Class、Method、Field、Constructor等。 以下是Java反射技术的...
写在前面的话 本篇blog实现了GridView的拖拽功能。方法和上一篇自定义ListView实现拖拽ListItem项交换位置一个原理。只是在交换位置上记录了X轴... import java.lang.reflect.Field; import java.util.ArrayList; impor
Android开发中我们经常需要用到将dip、px相互换算、获取手机屏幕的宽度...import java.lang.reflect.Field; /** * @author: xiaolijuan * @description: 屏幕分辨率工具类 * @date: 2016-06-05 * @time: 22:55 */
import java.lang.reflect.Field; import java.lang.reflect.Method; /** * */ /** * @ClassName: ReflectTest * @Description: TODO(这里用一句话描述这个类的作用) * @author zhoushun * @date 2013年11...
JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它...本文将谈到java.lang.Class,以及java.lang.reflect中的Method、Field、Constructor等等classes。
Class 类与 java.lang.reflect 类库一起对反射的概念进行了支持,该类库包含了 Field,Method,Constructor 类 (每个类都实现了 Member 接口)。这些类型的对象时由 JVM 在运行时创建的,用以表示未知类里对应的成员。...
import java.lang.reflect.InvocationTargetException; public class SimpleTest { /** *//** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub try { Constructor...
实现思路:利用单向链表来保存队列的数据,在往队列中添加元素的时候,新建一个...import java.lang.reflect.Field; public class MyLinkQueue { //头节点 private volatile Node head; //尾节点 private volati