java反射强转类型_java反射整理

反射可以说是在android源码中的影子无处不在,为了更好地理解android源码,所以该篇整理出反射中经常看到的用法,反射的代码是在运行时期运行,因此在编译器不会提示代码的错误性,只有在运行期才能检索代码,下面通过几个简单的例子来看看如何使用:

调用类的构造方法

写了一个简单的测试类:

package com.single.layoutinflaterdemo;

public class Reflection {

private String params1;

private int params2;

private long params3;

public Reflection() {

System.out.println("调用了Reflection类的无参数构造器");

}

public Reflection(String params1) {

this.params1 = params1;

System.out.println("调用了Reflection类的params1参数构造器====>params1:" + params1);

}

public Reflection(int params2) {

this.params2 = params2;

System.out.println("调用了Reflection类的params2参数构造器====>params2:" + params2);

}

public Reflection(long params3) {

this.params3 = params3;

System.out.println("调用了Reflection类的params3参数构造器====>params3:" + params3);

}

}

事例代码如下:

public static void main(String[] args) {

try {

Class clz = Class.forName("com.single.layoutinflaterdemo.Reflection");

Constructor appleConstructor1 = clz.getConstructor();

Object appleObj1 = appleConstructor1.newInstance();

Constructor appleConstructor2 = clz.getConstructor(String.class);

Object appleObj2 = appleConstructor2.newInstance("123");

Constructor appleConstructor3 = clz.getConstructor(int.class);

Object appleObj3 = appleConstructor3.newInstance(11);

Constructor appleConstructor4 = clz.getConstructor(long.class);

Object appleObj4 = appleConstructor4.newInstance(11l);

} catch (ClassNotFoundException e) {

e.printStackTrace();

} catch (NoSuchMethodException e) {

e.printStackTrace();

} catch (IllegalAccessException e) {

e.printStackTrace();

} catch (Instantiation

你可能感兴趣的:(java反射强转类型)