mercredi 22 avril 2015

Java - Pass private class to a method

So I have a neat little function which I can use to construct objects when my functions don't know what classes they'll be dealing with. (Yes I do have some nice uses for this before Soritos or anyone else wants to tell me I'm illogical)

public static Object Construct(Class type, Class[] params, Object[] values){
    //Create an object of any class
    try{
       Constructor con = type.getConstructor(params);
       Object o = con.newInstance(values);
       return o;
    }
    catch(Exception e){
       System.out.println("CONSTRUCTOR EXCEPTION"); 
       return null;
    }
}

Anyway I have a class declared within another class file that I want the main class to be able to pass to this function.

public class aClass {
   public aClass(String S, String s){
      Class c = otherClass.class;
      Object o = Functions.Construct(c, new Class[]{String.class, String.class}, new Object[]{S, s});
   }    
}

class otherClass{   
    public otherClass(String arg1, String arg2){}
}

But with this I get an exception. Is this because otherClass is not visible to my constructor function outside of this class?





Aucun commentaire:

Enregistrer un commentaire