手机版
你好,游客 登录 注册
背景:
阅读新闻

Java反射机制调用private类型的构造方法

[日期:2016-06-22] 来源:Linux社区  作者:yinxiaoqiexuxing [字体: ]

单例类:

package singleton;

public class SingletonTest {

    // 私有构造方法
    private SingletonTest(){
       
        System.out.println("无参数---构造----"); 
    }
    // 私有构造方法
    private SingletonTest(String a){
       
        System.out.println("有参数---构造----参数值:" + a); 
    }
    //定义私有类型的变量
    private static volatile  SingletonTest instance;
   
    //定义一个静态共有方法
    public static SingletonTest getInstance(){
       
        if(instance == null){
            synchronized(SingletonTest.class){
                if(instance == null){
                    return new SingletonTest();
                }
            }
        }
        return instance;
    }
}

测试调用类:

package reflect;

import Java.lang.reflect.Constructor;
import java.lang.reflect.Method;

import singleton.SingletonTest;

public class ReflectDemo {

    public static void main(String[] args) throws Exception{
        Class clazz = SingletonTest.class;

        /*以下调用无参的、私有构造函数*/ 
        Constructor c0=  clazz.getDeclaredConstructor(); 
        c0.setAccessible(true);
        SingletonTest po=(SingletonTest)c0.newInstance(); 
        System.out.println("无参构造函数\t"+po);

        /*以下调用带参的、私有构造函数*/ 
        Constructor c1=clazz.getDeclaredConstructor(new Class[]{String.class}); 
        c1.setAccessible(true); 
        SingletonTest p1=(SingletonTest)c1.newInstance(new Object[]{"我是参数值"}); 
        System.out.println("有参的构造函数\t"+p1); 

    }

}

输出结果:

无参数---构造----
无参构造函数 singleton.SingletonTest@11ff436
有参数---构造----参数值:我是参数值
有参的构造函数 singleton.SingletonTest@da3a1e

本文永久更新链接地址http://www.linuxidc.com/Linux/2016-06/132546.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款