Creative Coder
Creative Coder

Reputation: 418

Android : how to create a Object using Reflection and pass constructor parameter?

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.

Upvotes: 0

Views: 2779

Answers (1)

Mark Rotteveel
Mark Rotteveel

Reputation: 109001

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);

Upvotes: 4

Related Questions