0

I'm trying a button using reflection in android, by the following code

 public String createView(String classFullName){
        try{
            Class clazz = Class.forName(classFullName);

            Object obj = clazz.newInstance(); // but I need to pass the Context using this;


        }
        catch(ClassNotFoundException ex){
            return null;
        }
    }

but the main problem, is how to pass Context ( which is this in my case ) to the Object since they all should be a View.

1

1 Answer 1

4

The method Class#newInstance() is just a convenience method to invoke a zero-arg constructor. If you want to invoke a constructor with arguments, you need to obtain the right Constructor instance through reflection using Class#getConstructor(Class...), and then call it using Constructor#newInstance(Object...).

So:

Class clazz = Class.forName(classFullName);
Constructor<?> constructor = clazz.getConstructor(Context.class);
Object obj = constructor.newInstance(this);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.