最终目的:创建类Normal的一个实例并调用其方法say().
以下是解决方法及源码:
1、类Normal:
构造函数为私有的,外界根本不能直接创建对象
构造函数为私有的,外界根本不能直接创建对象
//Normal.java
package lianxi;
package lianxi;
public class Normal{
private Normal(){
System.out.println("构造函数被调用了");
}
private Normal(){
System.out.println("构造函数被调用了");
}
public void say(){
System.out.println("Hello Normal!");
}
}
2、测试类:
System.out.println("Hello Normal!");
}
}
2、测试类:
//Test.java
package lianxi;
import java.lang.reflect.*;
public class Test
{
public static void main(String args[]) throws Exception
{
Class cl=Class.forName("lianxi.Normal");
{
public static void main(String args[]) throws Exception
{
Class cl=Class.forName("lianxi.Normal");
//利用常用的反射方法破解封装,若构造方法为public,则可用以下方式实现,
//但对含有私有的构造方法的类是无效的
//Normal normal=(Normal)cl.newInstance();
//normal.say();
/*通过获取构造方法之后再创建实例
以下的getConstructor(new Class[]{})方法返回一个包含某些 Constructor 对象的数组,这些对
//normal.say();
/*通过获取构造方法之后再创建实例
以下的getConstructor(new Class[]{})方法返回一个包含某些 Constructor 对象的数组,这些对
象反映此 Class 对象所表示的类的所有公共构造方法。本例的Normal类的构造函数是PRIVATE,所以
无法获取构造方法,也就不能创建实例了
*/
//Constructor ct=cl.getConstructor(new Class[]{});
//System.out.println("构造器:"+ct);
/*
用getDeclaredConstructor()方法,无论构造方法是公有还是私有的都可以拿到构造器
再用constructor.setAccessible(true)设置允许访问私有的构造函数,这样就可以访问private类
*/
//Constructor ct=cl.getConstructor(new Class[]{});
//System.out.println("构造器:"+ct);
/*
用getDeclaredConstructor()方法,无论构造方法是公有还是私有的都可以拿到构造器
再用constructor.setAccessible(true)设置允许访问私有的构造函数,这样就可以访问private类
了, getDeclaredMethod():返回一个 Method 对象,该对象反映此 Class 对象所表示的类或接口的
指定已声明方法。
*/
Constructor ct=cl.getDeclaredConstructor(new Class[]{});
Method mt=cl.getDeclaredMethod("say",new Class[]{});
System.out.println("构造器:"+ct);
System.out.println("Method:"+mt);
ct.setAccessible(true);
//现在可以创建实例,并调用业务方法了
Normal normal=(Normal)ct.newInstance(new Object[]{});
normal.say();
}
};
*/
Constructor ct=cl.getDeclaredConstructor(new Class[]{});
Method mt=cl.getDeclaredMethod("say",new Class[]{});
System.out.println("构造器:"+ct);
System.out.println("Method:"+mt);
ct.setAccessible(true);
//现在可以创建实例,并调用业务方法了
Normal normal=(Normal)ct.newInstance(new Object[]{});
normal.say();
}
};
运行结果:
构造器:private src.test1.Normal()
Method:public void src.test1.Normal.say()
构造函数被调用了
Hello Normal!
Method:public void src.test1.Normal.say()
构造函数被调用了
Hello Normal!