How to pass a class and method to create an instance of a class?
Here is an article about instantiating classes by name in Swift. The problem is solved by creating an Objective-C class with method
+ (id)create:(NSString *)className
{
return [NSClassFromString(className) new];
}
and calling it from Swift.
The source code is on GitHub: https://github.com/ijoshsmith/swift-factory
UPDATE:
Here is a simpler solution:
var clazz: NSObject.Type = TestObject.self
var instance : NSObject = clazz()
if let testObject = instance as? TestObject {
println("yes!")
}
Of course, the class must be a subclass of NSObject.
Your function will then be:
func setClass (myClass: NSObject.Type){
var object = myClass()
}
How to pass in class to a method and call static methods on that class
You can do it with reflection and a capture-of wildcard; like
public PolymorphicFoobar(Class<? extends Foobar> cls) {
try {
Method sayHi = cls.getMethod("sayHi");
sayHi.invoke(cls);
} catch (Exception e) {
e.printStackTrace();
}
}
And then to invoke it, the syntax is very similar to what you had (you're missing new
, but otherwise the first form is good). Like,
public static void main(String[] args) {
new PolymorphicFoobar(Foo.class);
new PolymorphicFoobar(Bar.class);
}
Outputs
Hi from Foo!
Hi from Bar!
How do you pass an instance of a class as an argument for a method of that class?
The way to achieve this is correct. Just use another name, because class
is a reserved keyword for class definition
public static int methodA(ClassA instance) {
return 1;
}
How to create new instance of a class by passing Object[] instead of parameter list with reflection
The Class
method contains a getConstructor
method that takes an array of Class
as a parameter, corresponding to the constructor arguments. You have to build this array from your parameter array.
Something like that:
public <T> T getNewInstance(final Class<T> clazz, Object... constructorParameters) throws InstantiationException, IllegalAccessException, InvocationTargetException, SecurityException, NoSuchMethodException{
Class[] parameterTypes = new Class[constructorParameters.length];
for(int i = 0; i < constructorParameters.length; i++) {
parameterTypes[i] = constructorParameters[i].getClass();
}
Constructor<T> constructor = clazz.getConstructor(parameterTypes);
return constructor.newInstance(constructorParameters);
}
Edit: as Codebender said, this doesn't work when a subtype is passed as the argument.
passing class type as parameter and creating instance of it
Using reflection to create the instance:
Object obj = clazz.newInstance();
This will use the default no-arg constructor to create the instance.
Constructor<?> constructor = clazz.getConstructor(String.class);
Object object = constructor.newInstance(new Object[] { strArgument });
To create the instance if you have some other constructor which takes arguments.
How do I create an instance of a Class passed as parameter to a function?
You can have users pass a constructor reference:
fun helper(componentConstructor: ()->Component, props: Map<String, String>) : Component {
val component = componentConstructor()
// set it up and return it.
}
// usage:
val component = helper(::MyComponent, emptyMap())
Better for props
not to require a specific type of map since it doesn’t matter here. Needless burden for users of your library.
Pass any Class as a parameter for a method
In your latest edit, your usage example is like this:
ClassA test = doSomething("String One", ClassA.class);
The question shows confusion between a class name, the Class object and an instance of a class. So just to clarify, using the above example:
A class name –
ClassA
– is used to declare a variable.A Class instance –
ClassA.class
– is a singleton object that holds information about a class and can be passed as an argument to a method.An instance of a class –
test
– is an object. It's usually created using thenew
keyword.
You can't use a Class
object, such as ClassA.class
, directly in a declaration. Instead, you have to call the newInstance()
method of the Class
class. That method can be used only if your class has a no-args constructor. To create an instance with constructor arguments, use something like this:
public <T> T doSomething(String jsonString, Class<T> clazz) throws ReflectiveOperationException {
Constructor<T> constructor = clazz.getConstructor(String.class);
return constructor.newInstance(jsonString);
}
The above method creates an instance of the required class using a constructor that takes a String (the string that was passed in). Change its body to create an instance according to your requirements.
Related Topics
Apple-App-Site-Association Is Not Working
Using 'If-Case' Format in Boolean Assignment in Swift
How to Retrieve All Available Finder Tags
Check If a Character Is Lowercase or Uppercase
Firebasecore Lexical or Preprocessor Issue
How to Fix Error: Abort Trap 6 (In Target 'Realmswift' from Project 'Pods')
Catch Any Error, Specially Unexpectedly Found Nil in Swift
Can My Class Override Protocol Property Type in Swift
Migration from Swift 3 to Swift 4 - Cannot Convert String to Expected String.Element
How to Trigger Updateuiview of a Uiviewrepresentable
How to Import Googleanalytics Header into a Library Framework
How to Get the Url from Webview in Swift
Delay a Repeating Animation in Swiftui with Between Full Autoreverse Repeat Cycles
Using @Discardableresult for Closures in Swift
Swift 2 Error Handling and While
Iwatch: Wkinterfacelabel How to Stop Text from Being Cut Off with "..." at The End of a Label
Swift - How to Resize a Uiview Based on Its Uilabel Size (That Is Inside)