Create an instance of a class from a string name in Haxe - instantiation

Let's say i acquire the name of a class that i made as a String. How can i Instantiate the class with the name contained in that string? I I know it will be derived from a certain parent class, but the actual class will vary.

var instance : MyClass = Type.createInstance(Type.resolveClass("path.to.MyClass"), []);
Few notes:
resolveClass() takes the full path (packages included) of the classe you need
createInstance() takes as the second argument an array of values that are applied to the constructor. Those values must be in the exact number and must be passed even if they are optional (nulls are good in that case).

Related

how to write a meaningful test for `extending a class`?

what is the correct way to write a meaningful test for extending a class with the super keyword?
class FooBase<T> {
final T data;
const FooBase(this.data);
}
class Foo<T> extends FooBase<T> {
const Foo(T data)
: super(data);
}
I suppose super(data) ist passing the constructor parameter to the constructor of the base class (I do not know a lot about dart).
You can only test if super was called by observing its behavior. You have to check the base classes constructor for what it is doing with the parameter and then see if you can observe if that happened (if possible). Example: If the base class constructor is assigning the parameter to a field that you can access from the outside, you can assert on that parameter being set. This only works if
You can access the field from your test code. Access in this context does not mean to access it directly or via a getter. Any means of observing that the field has been set should be sufficient.
The class under test is not setting the field itself (there is probably no way to decide which constructor set the field).

Why do some Matlab class methods require "apparently" unnecessary output argument

After evolving my project code for months, I've finally hit a need to define a new class. Having to romp through my previous class definitions as a refresher of the conventions, I noticed that all constructors and property setters all have an output argument, even though nothing is assigned to it, e.g.:
function o = myConstructor( arg1, arg2, ... )
function o = set.SomeProperty( o, arg1 )
I've been looking through the documentation for upward of an hour without finding the explanation for this. It doesn't look like it depends on whether a function is defined in the class definition file or in its own separate m-file.
Can anyone please explain?
The best place to start is the documentation "Comparison of Handle and Value Classes". From the very top:
A value class constructor returns an object that is associated with the variable to which it is assigned. If you reassign this variable, MATLABĀ® creates an independent copy of the original object. If you pass this variable to a function to modify it, the function must return the modified object as an output argument.
A handle class constructor returns a handle object that is a reference to the object created. You can assign the handle object to multiple variables or pass it to functions without causing MATLAB to make a copy of the original object. A function that modifies a handle object passed as an input argument does not need to return the object.
In other words, value classes need to return a modified object (which is a new object distinct from the original), while handle classes don't. The constructor of either class will always have to return an object, since it is actually constructing it.
Some good additional reading is "Which Kind of Class to Use", which links to a couple helpful examples of each type of class object. Looking at the DocPolynom value class example, you can see that property set methods have to return the modified object, while the dlnode handle class example only requires an output for its constructor. Note that you could still return an object from a handle class method (if desired), but it's not required.

Can a structure inherit from a class in .NET?

I am confused about inheritance in .NET and here is why.
I was previously of the understanding that a structure cannot inherit from a class in .NET, so for example, the following won't compile:
struct MyStruct : MyClass
{
}
But today I read that integers (and other value types) are structs and not objects and they inherit from the ValueType class. The ValueType class inherits from System.Object and its purpose is to override certain methods in System.Object to make these methods suitable for Value Types.
So what's the deal? Can a structure inherit from a class in .NET, can it not or can it only in certain circumstances?
Thanks
Within the guts of .net, the definition for a struct containing certain members is the same as a definition for a class which those same fields and members, and which inherits from System.ValueType. Note that compilers will not allow one to declare a class which inherits ValueType, but when one declares a struct, the compiler, "behind the scenes" declares a class which does.
What makes value types special in .net is the way the run-time allocates storage locations (variables, fields, parameters, etc.) When a storage location of a type not inheriting from ValueType is declared, the runtime will allocate space for a heap object reference. By contrast, when a storage location of a type inheriting from ValueType is declared, the runtime will allocate space for all the public and private fields of that type. For a type like int, the system allocates a private field which is of a special primitive type, outside the normal type system.
Note that a storage location of a value type doesn't really hold an instance of that type; instead is an instance of that type, and holds all of the fields of that type. A statement like struct1 = struct2 does not replace the value-type instance struct1 with the instance struct2. Instead, it copies all of the fields from struct2 over the corresponding fields in struct1. Likewise if a value-type storage location is passed as a method to a procedure without using the ref keyword, what is passed is not the struct instance itself, but rather the contents of its fields.
If it is necessary to copy a value-type storage location to a one of type not derived from ValueType (e.g. Object or IComparable), the system will create a new heap-object instance of the value type, copy all the fields from the value type to that new instancen and store a reference to that new instance in the target storage location. This process is called "boxing". Most compilers will do this implicitly, thus attempting to behave as though a value type storage location holds an object which derives from ValueType. It's important to note, though, that this is an illusion. If type X derives from Y, one has an X named xx and a Y named yy, and one performs xx = yy, such a statement should cause xx and yy to refer to the same object instance. That will happen if xx and yy are types not derived from ValueType, even if yy holds an instance of something derived from ValueType. It will not happen, however, if xx and/or yy derives from ValueType. In that case, the system will copy fields from one instance to another (possibly new) instance.

Can instances get their own copy of class level mutable defaults without using __init__?

I'm writing a metaclass to do some cool stuff, and part of its processing is to check that certain attributes exist when the class is created. Some of these are mutable, and would normally be set in __init__, but since __init__ isn't run until the instance is created the metaclass won't know that the attribute will be created, and raises an error. I could do something like:
class Test(meta=Meta):
mutable = None
def __init__(self):
self.mutable = list()
But this approach has several problems:
it forces the creation of a class attribute that is not the same type as the instance attribute
__init__ still has to shadow the class attribute, and Meta is not checking that
if __init__ doesn't shadow the class attribute I'll still get errors down the line (such as AttributeError: 'NoneType' object has no attribute 'append'), and trying to avoid such errors is part of the function of Meta
and last but not least, it violates DRY.
What I need is a way to have something like:
class Test(metaclass=Meta):
mutable = list()
But each instance will end up with its own copy of mutable.
The design goals are:
the attribute must exist in the class (type doesn't matter -- it is not checked)
at some point before the attribute is first used a copy of the attribute is placed in the instance
A desired sample run:
t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
t1.mutable # prints ['one']
t2.mutable # prints ['two']
Any ideas on how this can be accomplished?
There are at least three ways to do this:
Have the metaclass check all the attributes, and if they are one of the mutables (list, dict, set, etc.) replace the attribute with a descriptor that will activate on first access and update the instance with a fresh copy of the mutable.
Provide the descriptor from (1) as a decorator to be used when writing the class.
Have the metaclass add its own __init__ method to the class which when run:
calls the original __init__
then checks that the required attributes are present
Downsides (by method):
Extra effort is required if the class has a mutable attribute that should be shared across all instances.
The attribute in the class becomes a function in the class (possible mind-warp ;)
Move the point of error to class instantiation instead of class definition.
I prefer (2) is it gives complete control to the class author, simplifies those cases where the class-level mutable attribute should be shared amongst all the instances, and keeps the error at class definition.
Here's the decorator-descriptor:
class ReplaceMutable:
def __init__(self, func):
self.func = func
def __call__(self):
return self
def __get__(self, instance, owner):
if instance is None:
return self
result = self.func()
setattr(instance, self.func.__name__, result)
return result
and the test class:
class Test:
#ReplaceMutable
def mutable():
return list()
How it works:
Just like property, ReplaceMutable is a descriptor object with the same name as the attribute it is replacing. Unlike property, it does not define __set__ nor __delete__, so when code tries to rebind the name (mutable in the test above) in the instance Python will allow it to do so. This is the same idea behind caching descriptors.
ReplaceMutable is decorating a function (with the name of the desired attribute) that simply returns whatever the instance level attribute should be initialized with (an empty list in the example above). So the first time the attribute is looked up on an instance it will not be found in the instance dictionary and Python will activate the descriptor; the descriptor then calls the function to retrieve the initial object/data/whatever, stores it in the instance, and then returns it. The next time that attribute is accessed on that instance it will be in the instance dictionary, and that is what will be used.
Sample code:
t1 = Test()
t2 = Test()
t1.mutable.append('one')
t2.mutable.append('two')
print(t1.mutable)
print(t2.mutable)

Scala: invoking superclass constructor

I am experiencing a weird behavior by Scala handling of superclass constructors.
I have a really simple class defined in the following way
package server
class Content(identifier:String,content:String){
def getIdentifier() : String = {identifier}
def getContent() : String = {content}
}
and a simple subclass
package server
class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){
override def getContent():String = {
println(content)
super.getContent
}
}
What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object
var c = new SubContent("x","x")
the execution of
c.getContent
first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).
Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.
It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.
The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.
Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":
If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.
However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.
(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.