In a project I am taking part in, there is a plethora of classes each implementing a method called add
which all work the same way, e.g. MyVector sum = add(vector1, vector2)
, where vector1
and vector2
are both of type MyVector
. I have no permission to modify of all the classes that have add
, so I could have make them implement some interface "IAddable
".
Now, I'd like to make a generic class of the form
class Summinator<TVector>
{
Function<TVector,TVector,TVector> add;
public Summinator()
{
//... somehow get the class of TVector, say cVector
Method addMethod = cVector.getDeclaredMethod("add", new Class[] {cVector, cVector});
add = (v1, v2) -> (TVector)addMethod.Invoke(null, v1, v2);
}
public TVector VeryLargeSum(TVector[] hugePileOfVectors)
{
TVector sum = hugePileOfVectors[0];
for (int i = 1; i < hugePileOfVectors.length; i++)
{
sum = add(sum, hugePileOfVectors[i]);
}
return sum;
}
}
As the sum is large, I'd like to have a lambda-expression to do the work. I also make type-checking at the initiation time. However, java wants me check for exceptions every time I invoke the method, so instead of
add = (v1, v2) -> (TVector)addMethod.Invoke(null, v1, v2);
it forces me to write something like
add = (v1, v2) ->
{
try {
return add.invoke(null, v1, v2);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
};
I am afraid that this exception-checking will consume lots of machine time, whereas all the objects are in fact quite basic in their nature and the application of add
is in fact a matter of a handful of flops. If it was C# and all classes in question had an overloaded + operation, I could have solved my problem with System.Linq.Expressions package, using the supported binary operations: there exception checking is not obligatory. But... I am to work in java.
Perhaps, there is some way around to at least ignore exception checking?
Aucun commentaire:
Enregistrer un commentaire