Vulkan/OpenGL enum name lookup

Hello, everyone. I wrote this code to help me understand Vulkan. It searches through the Vulkan classes to convert enum values to enum names. Here’s an example of it in action:

		VkSurfaceFormatKHR.Buffer formats = ...;
		System.out.println("    Surface formats: " + formats.limit());
		for(int i = 0; i < formats.limit(); i++){
			System.out.println("    Surface format " + (i+1) + ":");
			VkSurfaceFormatKHR format = formats.get(i);
			System.out.println("        Format: " + getEnumName("VK_FORMAT", format.format()));
			System.out.println("        Colorspace: " + getEnumName("VK_COLORSPACE", format.colorSpace()));
		}
		
		VkSurfaceFormatKHR format = formats.get(0);

		
		IntBuffer presentModes = ...;
		System.out.println("    Surface present modes: " + presentModes.limit());
		for(int i = 0; i < presentModes.limit(); i++){
			int presentMode = presentModes.get(i);
			System.out.println("        Surface present mode " + (i+1) + ": " + getEnumName("VK_PRESENT_MODE", presentMode));
		}

Output:

This is obviously only useful when debugging to make readable printouts, but it’s extremely powerful (thank you, Java reflection!) and easy to use. Here’s the code for getEnumName():


	private Class<?>[] enumClasses = new Class[]{
			VK10.class,
			KHRSurface.class,
			KHRSwapchain.class,
	};
	private String getEnumName(String prefix, int value){
		for(Class<?> c : enumClasses){
			for(Field f : c.getFields()){
				try {
					if(f.getName().startsWith(prefix) && (Integer)f.get(null) == value){
						return f.getName();
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return "Unknown enum " + value + " (0x" + Integer.toHexString(value) + ")";
	}

The enumClasses array can be tailor made so it only searches through the classes you use. Theoretically this function should work for OpenGL as well. In Vulkan each set of enums (formats, present modes, etc) all start at 0, but they’re all prefixed with the set they belong to. In OpenGL the enums do not start with the name of the enum set, but I do think that they’re unique in the entirety of OpenGL, so this function should still work for OpenGL too by just removing the prefix argument needed for Vulkan.