Clone a class instance

GIven this example

class Cat {
    public var name:String;
public function say_hello(){
trace("hello fron $name");
};
    public function new() {
        
    }
}

class Main {
    public static function main() {
        var c=new Cat();
        c.name="miki";
        var c2=c;
        c2.name="mouse";
        trace(c.name);
        trace(c2.name);
    }
}

Output

Main.hx:14: mouse
Main.hx:15: mouse

How could i clone the object instead of creating a reference (like [].copy()) or like clone in rust

Reflect.copy only copies filed, but not the methods (in JS target)

If cloning copies structure of the data, whereas copy does the same and copies the data, then you can do cloning via

var c2 = Type.createEmptyInstance(Type.getClass(c))

Thanks

But I want to keep the current fields, and only change the few fields I want

Then you need to copy, not to clone. Here is full sample showing how can be done versus anonymous object copy (Reflect.copy)

class Cat {
    public var name:String;
    public function say_hello(){
        trace("hello from "+name);
    };

    public function new() {
        
    }
}

class Cat2 extends Cat {
}

class Main {

    public static function copyClass<T>(c:T):T {
	var cls:Class<T> = Type.getClass(c);
    var inst:T = Type.createEmptyInstance(cls);
	var fields = Type.getInstanceFields(cls);
	for (field in fields) {
		var val:Dynamic = Reflect.field(c,field);
		if ( ! Reflect.isFunction(val) ) {
			Reflect.setField(inst,field,val);
		}
	}
	return inst;
    }

    public static function main() {
        var c=new Cat();
        c.name="miki";
	var c2 = copyClass(c);
	trace("old c2.name="+c2.name);
        c2.name="mouse";
	var c3 = new Cat2();
	c3.name = "miki2";
	var c4 = copyClass(c3);
       	c.say_hello();
        c2.say_hello();
        c3.say_hello();
        c4.say_hello();
	var o = { name:"", say_hello:(o)->trace("hello from "+o.name) }
	o.name="miki";
	var o2 = Reflect.copy(o);
	o2.name="mouse";
	o.say_hello(o);
	o.say_hello(o2);
    }
}
1 Like

Great. I would say its beneficial to add it to the stdlib