Android : 如何使用反射创建对象并传递构造函数参数?
Android : how to create a Object using Reflection and pass constructor parameter?
我正在尝试使用 android 中的反射按钮,代码如下
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;
}
}
但主要问题是如何将上下文(在我的例子中是这样)传递给对象,因为它们都应该是一个视图。
方法Class#newInstance()
只是调用零参数构造函数的便捷方法。如果要调用带参数的构造函数,则需要使用 Class#getConstructor(Class...)
, and then call it using Constructor#newInstance(Object...)
.
通过反射获取正确的 Constructor
实例
所以:
Class clazz = Class.forName(classFullName);
Constructor<?> constructor = clazz.getConstructor(Context.class);
Object obj = constructor.newInstance(this);
我正在尝试使用 android 中的反射按钮,代码如下
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;
}
}
但主要问题是如何将上下文(在我的例子中是这样)传递给对象,因为它们都应该是一个视图。
方法Class#newInstance()
只是调用零参数构造函数的便捷方法。如果要调用带参数的构造函数,则需要使用 Class#getConstructor(Class...)
, and then call it using Constructor#newInstance(Object...)
.
Constructor
实例
所以:
Class clazz = Class.forName(classFullName);
Constructor<?> constructor = clazz.getConstructor(Context.class);
Object obj = constructor.newInstance(this);