This is an old revision of the document!
Table of Contents
Method
The conversion can be declared as a method between to classes. It is possible to declare this method on either of the two class for either of the conversion side. E.g. to convert A to B it is possible to declare a method in A, or in B, that define how A should be converted.
From the source of the conversion
In the example where A will be converted to B, and A declare the conversion methods there is one possible method, which can also be applied for array. The method has to:
- be NON static
- return an object of the type of the conversion target. (B, or B[] in this example)
- have 0 arguments
- be called
to + NAME_OF_TYPE, orto + NAME_OF_TYPE + Arrayto convert to the type or an array of the type respectively (where NAME_OF_TYPE is the name of the conversion target type).
class A{ B toB(){ return new B(); } B[] toBArray(){ return new B[0]; } } class B {} public void run () { B b = new A(); B[] ar = new A(); }
From the target of the conversion
It is also possible to declare the conversion methods in the target type of the conversion. In that case the methods can either be valueOf, or to + NAME_OF_TYPE.
valueOf
The method valueOf need to follow the rules:
- be static
- return the target type
- be called
valueOf - have exactly one argument of the source type
class A{} class B { static B valueOf(A b){ return new A(); } } public void run () { B b = new A(); }
toType
(NOT recommended)
The method toType has to follow the rules: (it is different from the toType in the conversion source)
- be static
- return an object of the type of the conversion target. (B, or B[] in this example)
- have exactly 1 argument of the type of the source of the conversion (A in this example)
- be called
to + NAME_OF_TYPE - the source type HAS to be imported statically
- an method with the same rules (static, toType, same return type and argument type) need to be declared in the source type as well.
Due to the two last required points, I don't see the use of this method.
