How to convert between "similar" 3D-vector classes in java?
I'm writing a geom package as part of a Java library that has its own vector class:
package mypackage.geom;
public class Vector3D {
public float x;
public float y;
public float z;
public Vector3D(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
}
...
}
My library is expected to complement the functionality of a third party library which also implements a vector class, say Vec3D
. The Vec3D
class has the same fields (float x
, float y
and float z
) and constructor signatures as my Vector3D
class. I just want to use the third party vector class everywhere a Vector3D
parameter is expected in my library (e.g., Suppose I have a Camera
class that has a setPosition(Vector3D vector3D)
method, and I want be able to pass a Vec3D
instance to it).
This is possible in C++. For instance, one can 开发者_如何学编程declare an universal explicit converter constructor from any class to Vector3D, in the following way:
template <class C>
explicit Vector3D(const C& c) : x(c[0]), y(c[1]), z(c[2]) {}
all that it requires is that the foreigner class implements the operator[]
. I was wondering how to implement something similar in Java, if possible at all.
There are a few options, none of them as nice as what you show. First, of course, you can write an explicit constructor:
Vector3d(Vec3d v) {this.x = v.x; this.y = v.y; this.z = v.z; }
Second, you could provide a constructor that worked for any vector type that implemented an interface you would define (call it "V":)
Vector3d(V v) {this.x = v.getX(); this.y = v.getY(); this.z = v.getZ(); }
Of course, the chance that any random vector-like thing would implement V is pretty much 0, unless you're a standards body of some kind.
You could also provide a constructor that takes a double[]
, under the assumption that most such types will provide a toArray()
sort of method:
Vector3d(double[] v) {this.x = v[0]; this.y = v[1]; this.z = v[2]; }
This would make it relatively easy to convert most other vector classes into yours, without adding a custom constructor.
I think this comes closest to your converter constructor from any (unknown) kind of class:
public vec(Object any)
{
try {
x = any.getClass().getDeclaredField("x").getDouble(any);
y = any.getClass().getDeclaredField("y").getDouble(any);
z = any.getClass().getDeclaredField("z").getDouble(any);
} catch ( Exception e ) {
throw(new RuntimeException("vec cannot handle class in constructor: "+any.getClass(),e));
}
}
精彩评论