|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?快速注册
×
JAVA 私塾笔记整理——反射机制(Reflection)
一.反射是什么?
反射它允许运行中的 Java 程序对自身进行检查,或者说“自审”,并能直接操作程序的内部属性。
二.分析类的构成?
1.获取Class对象:
Class c = Class.forName("java.lang.String");
Class c = int.class;
Class c = Integer.TYPE;
*它们可获得基本类型的类信息。其中后一种方法中访问的是基本类型的封装类 (如Integer) 中预先定义好的 TYPE 字段。
2.获取类的方法
- package cn;
- import java.lang.reflect.*;
- public class Test {
- ∵ int f1(Object p, int x) throws NullPointerException {
- if (p == null)
- throw new NullPointerException();
- return x;
- }
- public static void main(String args[]) {
- try {
- Class cls = Class.forName("cn.Test");
- Method methlist[] = cls.getDeclaredMethods();
- for (int i = 0; i < methlist.length; i++) {
- Method m = methlist[i];
- System.out.println("name = " + m.getName());
- System.out.println("decl class = " + m.getDeclaringClass());
- Class pvec[] = m.getParameterTypes();
- for (int j = 0; j < pvec.length; j++)
- System.out.println("param #" + j + " " + pvec[j]);
- Class evec[] = m.getExceptionTypes();
- for (int j = 0; j < evec.length; j++)
- System.out.println("exc #" + j + " " + evec[j]);
- System.out.println("return type = " + m.getReturnType());
- System.out.println("-----");
- }
- } catch (Throwable e) {
- System.err.println(e);
- }
- }
- }
复制代码 输出的结果如下:
name = f1
decl class = class cn.Test
param #0 class java.lang.Object
param #1 int
exc #0 class java.lang.NullPointerException
return type = int
-----
name = main
decl class = class cn.Test
param #0 class [Ljava.lang.String;
return type = void
-----
3. 获取构造器
- package cn;
- import java.lang.reflect.*;
- public class Test {
- public Test() {}
- protected Test(int i, double d) {
- }
- public static void main(String args[]) {
- try {
- Class cls = Class.forName("cn.Test");
- Constructor ctorlist[] = cls.getDeclaredConstructors();
- for (int i = 0; i < ctorlist.length; i++) {
- Constructor ct = ctorlist[i];
- System.out.println("name = " + ct.getName());
- System.out.println("decl class = " +
- ct.getDeclaringClass());
- Class pvec[] = ct.getParameterTypes();
- for (int j = 0; j < pvec.length; j++)
- System.out.println("param #" + j + " " + pvec[j]);
- Class evec[] = ct.getExceptionTypes();
- for (int j = 0; j < evec.length; j++)
- System.out.println("exc #" + j + " " + evec[j]);
- System.out.println("-----");
- }
- } catch (Throwable e) {
- System.err.println(e);
- }
- }
- }
复制代码 这个程序运行的结果是:
name = cn.Test
decl class = class cn.Test
-----
name = cn.Test
decl class = class cn.Test
param #0 int
param #1 double
-----
4. 获取类的属性字段(域字段)
- package cn;
- import java.lang.reflect.*;
- public class Test {
- ∵ double d;
- public static final int i = 37;
- String s = "testing";
- public static void main(String args[]) {
- try {
- Class cls = Class.forName("cn.Test");
- Field fieldlist[] = cls.getDeclaredFields();
- for (int i = 0; i < fieldlist.length; i++) {
- Field fld = fieldlist[i];
- System.out.println("name = " + fld.getName());
- System.out.println("decl class = " + fld.getDeclaringClass());
- System.out.println("type = " + fld.getType());
- int mod = fld.getModifiers();
- System.out.println("modifiers = " + Modifier.toString(mod));
- System.out.println("-----");
- }
- } catch (Throwable e) {
- System.err.println(e);
- }
- }
- }
复制代码 这个程序的输出是:
name = d
decl class = class cn.Test
type = double
modifiers = ∵
-----
name = i
decl class = class cn.Test
type = int
modifiers = public static final
-----
name = s
decl class = class cn.Test
type = class java.lang.String
modifiers =
-----
三.如何动态调用
(要动态调用就要创建实例)
Class cls = Class.forName("cn.Test");
Object obj = cls.newInstance();
*使用反射机制的主流框架都是默认调用无参的public构造器,所以我们不能改类的构造器。
四.设计实现javaBean功能
- import java.lang.reflect.Field;
- import java.lang.reflect.Method;
- import java.util.HashMap;
- import java.util.Map;
- public class JavaBean {
- ∵ static Object myJavaBean(Map map,Class cls) throws Exception{
- //得到类中所有字段
- Field fs[] = cls.getDeclaredFields();
- //new 一个实例
- Object obj = cls.newInstance();
- for(int i=0;i<fs.length;i++){
- //得到字段名
- Object v = map.get(fs[i].getName());
- if(v!=null){
- //只有一个参数
- Class partypes[] = new Class[1];
- partypes[0] = fs[i].getType();
- //拼setter方法
- Method meth = cls.getMethod("set"
- + fs[i].getName().substring(0,1).toUpperCase()
- + fs[i].getName().substring(1), partypes);
- Object arglist[] = new Object[1];
- arglist[0] = v;
- meth.invoke(obj, arglist);
- }
- }
- return obj;
- }
-
- public static void main(String[] args) throws Exception {
- Map map = new HashMap();
- map.put("userId", "1234");
- map.put("name", "4321");
- map.put("ddd", "dddd dddd");
- Object obj = myJavaBean(map,AModel.class);
- AModel am = (AModel)obj;
- System.out.println("am.userId=" + am.getUserId() + ",name=" + am.getName());
- }
- }
- class AModel{
- ∵ String userId,name;
- public String getUserId() {
- return userId;
- }
- public void setUserId(String userId) {
- this.userId = userId;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- }
复制代码 这个程序的输出是:
am.userId=1234,name=4321
JAVA 私塾经典学习视频,可以到官网下载观看,w ww.javass.cn |
|