I am trying to instantiate a class from string, but it is not working because of generics.
I have this class declaration:
class PollSummaryView<T: PollSummary>: UIView {}
And then many subclasses:
class TextPollSummaryView: PollSummaryView<TextPollSummary> {}
class ChartingPollSummaryView: PollSummaryView<ChartPollSummary> {}
Then, I am trying to instantiate doing this:
let contentClassName = "\(summary.poll.type.rawValue)PollSummaryView"
let contentClass = classFromString(contentClassName) as? PollSummaryView.Type
But it is getting nil. Also tried this with same results:
let contentClassName = "\(summary.poll.type.rawValue)PollSummaryView"
let contentClass = classFromString(contentClassName) as? PollSummaryView<PollSummary>.Type
Just in case, this the classFromString snippet:
func classFromString(_ className: String) -> AnyClass? {
let namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String;
let cls: AnyClass? = NSClassFromString("\(namespace).\(className)");
return cls;
}
In Java Android I am doing this:
public static @Nullable
<T extends PollSummaryView> T createView(PollSummary summary, Context context) {
try {
String simpleClassName = StringUtils.capitalize(summary.getPoll().getType().name()).concat("PollSummaryView");
String className = String.format("%s.%s", getPackage(), simpleClassName);
Class<? extends PollSummaryView> clazz = Class.forName(className).asSubclass(PollSummaryView.class);
return (T) clazz.getConstructor(summary.getClass(), Context.class).newInstance(summary, context);
} catch (Exception e) {
return null;
}
}
And it works, but warning about an unchecked cast.
Is there any Swift expert over there?
Many thanks!
Aucun commentaire:
Enregistrer un commentaire