Overwrite - Revxrsal/Tuna-Bytes GitHub Wiki
Overwrite
s are a powerful feature of mixins that allow to completely overwrite the code of a certain method.
Let's say we have this simple Employee
class
public class Employee {
private final String name;
private final double salary;
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}
Pretty boring.. right? Well, let's say that the company needs to lower the salaries of its employees to due to high labor costs
import io.tunabytes.Mixin;
import io.tunabytes.Overwrite;
import io.tunabytes.Mirror;
@Mixin(Employee.class)
public class EmployeeMixin {
@Mirror private double salary;
@Overwrite
public double getSalary() {
return salary - 2000;
}
}
Now, all employees will have 2000 deducted from their salaries. We can verify that:
public class EmployeeTest {
public static void main(String[] args) {
MixinsBootstrap.init();
Employee employee = new Employee("David", 4000);
System.out.println("Salary: " + employee.getSalary());
}
}
Output:
Salary: 2000.0
Note 1: When overwriting, it is quite possible that you may need to reference to the class fields or other methods. In that case, take a look at mirroring.
Note 2: Quite often, overwriting is an overkill and we only need to do a simple addition to the method code. If this is the case, check injecting.
Note 3: Having multiple @Overwrite
s on the same method would simply lead to one overwrite being dismissed. Hence, it is not recommended to have more than one @Overwrite
for each method, and when possible: use injection.