构造函数可以使用return来结束函数。
摘自String.class
/**
* Package private constructor. Trailing Void argument is there for
* disambiguating it against other (public) constructors.
*
* Stores the char[] value into a byte[] that each byte represents
* the8 low-order bits of the corresponding character, if the char[]
* contains only latin1 character. Or a byte[] that stores all
* characters in their byte sequences defined by the {@code StringUTF16}.
*/
String(char[] value, int off, int len, Void sig) {
if (len == 0) {
this.value = "".value;
this.coder = "".coder;
return;
}
if (COMPACT_STRINGS) {
byte[] val = StringUTF16.compress(value, off, len);
if (val != null) {
this.value = val;
this.coder = LATIN1;
return;
}
}
this.coder = UTF16;
this.value = StringUTF16.toBytes(value, off, len);
}
在构造函数里使用了某些不一定能成功的操作,然后想在对这个类进行new操作的时候返回NULL。不过在构造函数里return以后,只是构造函数后面的步骤不走了,但new操作仍然成功。
不一定成功的操作,可以进行抛出异常。
摘自Color.class
/**
* Creates an sRGB color with the specified red, green, blue, and alpha
* values in the range (0 - 255).
*
* @throws IllegalArgumentException if {@code r}, {@code g},
* {@code b} or {@code a} are outside of the range
* 0 to 255, inclusive
* @param r the red component
* @param g the green component
* @param b the blue component
* @param a the alpha component
* @see #getRed
* @see #getGreen
* @see #getBlue
* @see #getAlpha
* @see #getRGB
*/
@ConstructorProperties({"red", "green", "blue", "alpha"})
public Color(int r, int g, int b, int a) {
value = ((a & 0xFF) << 24) |
((r & 0xFF) << 16) |
((g & 0xFF) << 8) |
((b & 0xFF) << 0);
testColorValueRange(r,g,b,a);
}
/**
* Checks the color integer components supplied for validity.
* Throws an {@link IllegalArgumentException} if the value is out of
* range.
* @param r the Red component
* @param g the Green component
* @param b the Blue component
**/
private static void testColorValueRange(int r, int g, int b, int a) {
boolean rangeError = false;
String badComponentString = "";
if ( a < 0 || a > 255) {
rangeError = true;
badComponentString = badComponentString + " Alpha";
}
if ( r < 0 || r > 255) {
rangeError = true;
badComponentString = badComponentString + " Red";
}
if ( g < 0 || g > 255) {
rangeError = true;
badComponentString = badComponentString + " Green";
}
if ( b < 0 || b > 255) {
rangeError = true;
badComponentString = badComponentString + " Blue";
}
if ( rangeError == true ) {
throw new IllegalArgumentException("Color parameter outside of expected range:"
+ badComponentString);
}
}
或者new成功后再进行一次判断。