怎么用Class.forName("....");获得一个构造函数为private class的实例?

解决方案 »

  1.   

    怎么用Class.forName("....");获得一个构造函数为private class的实例?既然是私有的构造方法,那么这个类必然有一个得到类对象的静态方法哦
    要不然是不能实例化这个类了
      

  2.   

    package tony.designpattern.singleton;import java.lang.reflect.*;public class Test {    public static void main(String[] args) {
            try {
                Class c = Class
                        .forName("tony.designpattern.singleton.LazySingleton");
                Method[] methods = c.getMethods();
                for (int i = 0; i < methods.length; i++) {
                    String className = methods[i].getReturnType().toString();
                    if (className.indexOf(".") > 0) {
                        className = className
                                .substring(className.lastIndexOf(".") + 1);
                        System.out.println("className:" + className);
                        if (className.equals("LazySingleton")) {//返回类型是这个的类
                            // if (methods[i].getModifiers() == Method.) {//原先想判断是否是static的
                            LazySingleton singleton = (LazySingleton) methods[i]
                                    .invoke(null, null);//静态方法可以不用实例,所以可以用null
                            // System.out.println(singleton instanceof
                            // LazySingleton);
                            singleton.print();
                            // }
                        }
                    }
                }
            } catch (Exception e) {
            }    }}
    ------------------------------------
    package tony.designpattern.singleton;/**
     * Description:
     * 
     * @author Tony.Fang
     * @version 0.1
     *  
     */
    public class LazySingleton {    private static LazySingleton lazySingleton = null;
        private int i = 0;
        
        private LazySingleton() {
        }    synchronized public static LazySingleton getInstance() {
            if (lazySingleton == null) {
                lazySingleton = new LazySingleton();
            }
            return lazySingleton;
        }    public void print() {
            
            System.out.println("lazySingleton:"+i++);
        }
    }
      

  3.   

    要用反射,做个例子给你
    //test.Test1
    package test;public class Test1 {
    private int i; private Test1(int i) {
    this.i = i;
    }
    public void test() {
    System.out.println(i);
    }
    }
    //test.Test2
    package test;import java.lang.reflect.Constructor;
    import java.lang.reflect.Method;public class Test2 {
    public static void main(String[] args) throws Exception {
    Class c = Class.forName("test.Test1");
    Constructor constructor = c.getDeclaredConstructor(new Class[] { int.class });
    constructor.setAccessible(true);
    Object o = constructor.newInstance(new Object[] { new Integer(10) });
    Method testMethod = c.getMethod("test", null);
    testMethod.invoke(o, null);
    }
    }
    你试一下就明白了。
    但构造函数一定要存在。
      

  4.   

    spring 中的 bean 默认就是 singleton 的,但也不一定有静态的工厂方法啊。
      

  5.   

    如果只有一个private的构造函数,想通过Class.forName()是不可能实现的。
    必须得借助public的或者public static的
      

  6.   

    to westwin(浮躁的很)
    很支持你的 title。
      

  7.   

    上面的两个方法都可,推荐 haha1903(中国人) 的。import java.lang.reflect.*;public class PrivateConstructor {    public static void main(String[] args) throws Exception  {
         get2("LazySingleton");
         get1("LazySingleton");
        }
        
        static void get1(String className) throws ClassNotFoundException, IllegalArgumentException, IllegalAccessException, InvocationTargetException{
            Class c = Class.forName(className);
            Method[] methods = c.getMethods();
            for (int i = 0; i < methods.length; i++) {
                String mType = methods[i].getReturnType().toString();
                System.out.println("mType:" + mType);
                if (className.indexOf("LazySingleton") > 0) {
                    // if (methods[i].getModifiers() == Method.) {//judge if to be static
                    LazySingleton singleton = (LazySingleton) methods[i]
                            .invoke(null, null);//(null) for static method
                    // System.out.println(singleton instanceof
                    // LazySingleton);
                    singleton.print();
                    // }
                }
            }
        }
        
        static void get2(String className) throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException{
    Class c = Class.forName(className);
    Constructor constructor = c.getDeclaredConstructor(new Class[] { int.class });
    constructor.setAccessible(true);
    Object obj = constructor.newInstance(new Object[] { new Integer(10) });
    Method testMethod = c.getMethod("print", null);
    testMethod.invoke(obj, null);
        }
    }
    public class LazySingleton {    private static LazySingleton lazySingleton = null;
        private int i = 0;
        
        private LazySingleton() {
        }
        
        private LazySingleton(int n) {
         i = n;
        }    synchronized public static LazySingleton getInstance() {
            if (lazySingleton == null) {
                lazySingleton = new LazySingleton();
            }
            return lazySingleton;
        }    public void print() {
            System.out.println("lazySingleton:"+i++);
        }
    }
      

  8.   

    楼上已经说的很清楚了  get1里边如果需要通过反射调用其他的方法则:
     Method meth = c.getMethod("print", null);
    meth.invoke(singleton ,null);
      

  9.   

    constructor.setAccessible(true);这个不一定总是成功,应为涉及到权限。如果是private,我想需要有一个static的方法返回这个类的事例。那么invoke这个方法比较好。