java reflection 替代_java reflection总结

一、java反射常用方法

获取Class的几种方式:

Class class1 = String.class;// 该方法最为安全可靠,程序性能更高。 Class class2 = string.getClass(); Class class3 = Class.forName("java.lang.String");// 可能抛出ClassNotFoundException异常

Class class = Integer.TYPE;//不能用第一种方式

获取内部类:

getDeclaredClasses()

获取本类中声明的字段:

getDeclaredFields()

getDeclaredField(String name)

获取本类中声明的方法:

getDeclaredMethods()

getDeclaredMethod(String name, Class...> parameterTypes)

获取本类中声明的构造函数

getDeclaredConstructors()

getDeclaredConstructor(Class...> parameterTypes)

通过反射设置字段属性(还有方法来获取,get(Object object))

set(Object object, Object value)

通过反射调用方法(也可以获取方法的一些其他属性)

invoke(Object receiver, Object... args)

通过反射生成对象(也可以获取构造函数的一些其他属性)

newInstance(Object... args)

二、Java Annotation

这部分在代码注释中去理解。

三、改变字段(域)的值

Field.java

import java.lang.reflect.*;

public class Field2 {

public double d;

public static void main(String args[]) {

try {

Class cls = Class.forName("Field2");

Field fld = cls.getField("d");

Field2 f2obj = new Field2();

System.out.println("d = " + f2obj.d);

fld.setDouble(f2obj, 12.34);

System.out.println("d = " + f2obj.d);

}

catch (Throwable e) {

System.err.println(e);

}

}

}

输出结果:

9fe666e2db18d0d00b045e71708dc861.png

四、根据方法的名称来执行方法

Method2.java

import java.lang.reflect.*;

public class Method2 {

public int add(int a, int b) {

return a + b;

}

public static void main(String args[]) {

try {

Class cls = Class.forName("Method2");

//Class partypes[] = new Class[2];

//partypes[0] = Integer.TYPE;

//partypes[1] = Integer.TYPE;

Method meth = cls.getMethod("add", new Class[]{Integer.TYPE,Integer.TYPE});

Method2 methobj = new Method2();

//Object arglist[] = new Object[2];

//arglist[0] = new Integer(37);

//arglist[1] = new Integer(47);

Object retobj = meth.invoke(methobj, new Object[]{new Integer(37),new Integer(47)});

Integer retval = (Integer) retobj;

System.out.println(retval.intValue());

}

catch (Throwable e) {

System.err.println(e);

}

}

}

五、创建新的对象

Constructor2.java

import java.lang.reflect.*;

public class Constructor2 {

public Constructor2() {

}

public Constructor2(int a, int b) {

System.out.println("a = " + a + " b = " + b);

}

public static void main(String args[]) {

try {

Class cls = Class.forName("Constructor2");

//Class partypes[] = new Class[2];

//partypes[0] = Integer.TYPE;

//partypes[1] = Integer.TYPE;

Constructor ct = cls.getConstructor(new Class[]{Integer.TYPE,Integer.TYPE});

//Object arglist[] = new Object[2];

//arglist[0] = new Integer(37);

//arglist[1] = new Integer(47);

Object retobj = ct.newInstance(new Object[]{new Integer(37),new Integer(47)});

}

catch (Throwable e) {

System.err.println(e);

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值