lundi 5 juin 2017

Java Getting NullPointerException when calling the construtor using Reflection

I'm using refletion to call the construtor of a certain class (i receive the name of the class as string) and the i pass as a arguments a String and an object

Something like that:

private void callClassByName(String className) {
String s = "Hello";
SomeClass someClass = new SomeClass(); //Initialize the class
        try {
            Class<?> clazz = Class.forName(className);
            Constructor<?> ctor = clazz.getConstructor(String.class, SomeClass.class ); //Pass the 2 args
            Object object = ctor.newInstance(s, someClass);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Class Called

    private SomeClass someClass;


    //Construtor
    public HelloClass(String fieldValue, SomeClass someClass) {         
       this.someClass = someClass; //Initialize
    }

So, i'm getting a NullPointerException (on the clazz.getConstructor's line) and since i'm initialize the class i dont know why i'm getting this error. And i also saw some examples but they were all about static methods and i'm working on the construtor

Thanks you for your time





Aucun commentaire:

Enregistrer un commentaire