您的位置:首页 > 编程语言 > Java开发

java开发之构造方法的反射应用

2016-11-10 08:23 411 查看
Constructor类代表某一个类中的一个构造方法

得到某个类的所有构造方法:

Constructor<?>[] constructors = String.class.getConstructors();
得到某一个构造方法:

Constructor<String> constructor = String.class.getConstructor(StringBuffer.class);</span>


创建实例对象:

通常方法:

String str = new String(new StringBuffer("abc"));
反射方法:

String str = constructor.newInstance(new StringBuffer("abc"));


私有的构造方法:

我们知道一个对象如果将构造方法私有化,那么就只能从内部来实例化该对象,其实不然,通过反射,我们仍然可以从外部来实例化该对象

得到某个类私有的构造方法:

Constructor<Test> constructor = Test.class.getDeclaredConstructor();
这样就可以获取到这个类的无参数的私有构造方法,但是我们虽然获取到了它的构造方法,但是我们不能直接使用它来实例化对象

要使用constructor.setAccessible(true);之后才能实例化该对象

创建实例对象:

public class Test{
private Test(){}
}


try {
Constructor<Test> constructor = Test.class.getDeclaredConstructor();
constructor.setAccessible(true);
Test test = constructor.newInstance();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}


内部类的反射:

一个内部类的实例化是依靠外部类的,即先有外部类才有内部类,其实内部类的构造方法的第一个参数就是外部类

内部类的实例化:

public class Test{
private Test(){}
class Test1{

}
}


try {
Constructor<Test> constructor = Test.class.getDeclaredConstructor();
constructor.setAccessible(true);
Test test = constructor.newInstance();

Constructor<Test1> constructor1 = Test1.class.getDeclaredConstructor(Test.class);
Test1 test1 = constructor1.newInstance(test);

} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}

Android开发交流群:245461612
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐