为什么Java方法Enum.valueof调用枚举类型构造函数?

时间:2018-08-18 00:22:46

标签: java enums

我已经建立了这种数据枚举:

enum Sexo {
    HOMBRE("H"), MUJER("M"), OTRO("O"); 
    private String sexo;        
    private Sexo(String sexo){ 
        System.out.println("constructor del tipo enum");
        this.sexo=sexo;
    }
 }

然后,在Main方法中,我只是这样做:

public static void main(String[] args) {

    Sexo sexo1 = Enum.valueOf(Sexo.class, "HOMBRE"); 
    Sexo sexo2 = Enum.valueOf(Sexo.class, "MUJER"); 
    Sexo.valueOf("OTRO");

}

然后,我在控制台上找到它:

constructor del tipo enum
constructor del tipo enum
constructor del tipo enum

我知道我对每个枚举类型都有一个构造函数的调用,而句子“ Sexo”(枚举类型的名称)。但: 为什么构造函数只运行一次?请注意,我有两个实例,一个直接调用该类。

1 个答案:

答案 0 :(得分:3)

调用构造函数的方法不是protected Image readImage(String path, Display display) { InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream(path); BufferedImage bi = null; try { bi = ImageIO.read(stream); } catch (IOException e) { e.printStackTrace(); } finally { try { if (stream != null) stream.close(); } catch (IOException e) { e.printStackTrace(); } } return new Image(display, convertToSWT(bi)); } public static ImageData convertToSWT(BufferedImage bufferedImage) { if (bufferedImage.getColorModel() instanceof DirectColorModel) { DirectColorModel colorModel = (DirectColorModel) bufferedImage.getColorModel(); PaletteData palette = new PaletteData( colorModel.getRedMask(), colorModel.getGreenMask(), colorModel.getBlueMask() ); ImageData data = new ImageData( bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette ); WritableRaster raster = bufferedImage.getRaster(); int[] pixelArray = new int[3]; for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { raster.getPixel(x, y, pixelArray); int pixel = palette.getPixel( new RGB(pixelArray[0], pixelArray[1], pixelArray[2]) ); data.setPixel(x, y, pixel); } } return data; } else if (bufferedImage.getColorModel() instanceof IndexColorModel) { IndexColorModel colorModel = (IndexColorModel) bufferedImage.getColorModel(); int size = colorModel.getMapSize(); byte[] reds = new byte[size]; byte[] greens = new byte[size]; byte[] blues = new byte[size]; colorModel.getReds(reds); colorModel.getGreens(greens); colorModel.getBlues(blues); RGB[] rgbs = new RGB[size]; for (int i = 0; i < rgbs.length; i++) { rgbs[i] = new RGB(reds[i] & 0xFF, greens[i] & 0xFF, blues[i] & 0xFF); } PaletteData palette = new PaletteData(rgbs); ImageData data = new ImageData( bufferedImage.getWidth(), bufferedImage.getHeight(), colorModel.getPixelSize(), palette ); data.transparentPixel = colorModel.getTransparentPixel(); WritableRaster raster = bufferedImage.getRaster(); int[] pixelArray = new int[1]; for (int y = 0; y < data.height; y++) { for (int x = 0; x < data.width; x++) { raster.getPixel(x, y, pixelArray); data.setPixel(x, y, pixelArray[0]); } } return data; } return null; }

第一次使用该类时,将为每个文字调用valueOf的构造函数。因此,在您的情况下,那就是在首次调用enum之前。

对构造函数的三个调用是由三个文字引起的,而不是对Enum.valueOf的三个调用。