jeudi 16 avril 2015

Why doesn't java provide implicit reflection? [duplicate]


This question already has an answer here:




Example from another stackoverflow thread link:



public class RegularEmployee {
private BigDecimal salary;

public void setSalary(BigDecimal salary) {
this.salary = salary;
}

public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".02");
}

public BigDecimal calculateBonus() {
return salary.multiply(getBonusMultiplier());
}

/* ... presumably lots of other code ... */
}

public class SpecialEmployee extends RegularEmployee {
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".03");
}
}


This doesn't behave as some people might think, because calculateBonus always takes the getBonusMultiplier from RegularEmployee, even if called from an instance of SpecialEmployee.



public class RegularEmployee {
private BigDecimal salary;

public void setSalary(BigDecimal salary) {
this.salary = salary;
}

public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".02");
}

public BigDecimal calculateBonus() {
try {
return salary.multiply((BigDecimal) this.getClass().getMethod("getBonusMultiplier").invoke(null));
} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
Logger.getLogger(Parent.class.getName()).log(Level.SEVERE, null, ex);
}
}

/* ... presumably lots of other code ... */
}

public class SpecialEmployee extends RegularEmployee {
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".03");
}
}


This does call the getBonusMultiplier() from SpecialEmployee if called from a SpecialEmployee instance.


My question is: why doesn't Java provide implicit use of reflection like this? The code would be much more readable if I could achieve the same with:



public class RegularEmployee {
private BigDecimal salary;

public void setSalary(BigDecimal salary) {
this.salary = salary;
}

public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".02");
}

public BigDecimal calculateBonus() {
return salary.multiply(origin.getBonusMultiplier());
}

/* ... presumably lots of other code ... */
}

public class SpecialEmployee extends RegularEmployee {
public static BigDecimal getBonusMultiplier() {
return new BigDecimal(".03");
}
}





Aucun commentaire:

Enregistrer un commentaire