Java constant examples (Create a java file having only constants)

前端 未结 5 785
别那么骄傲
别那么骄傲 2021-01-31 03:14

What is the best practice to declare a java file having only constant?

public interface DeclareConstants
{
    String constant = \"Test\";
}

OR

5条回答
  •  忘掉有多难
    2021-01-31 03:39

    You can also use the Properties class

    Here's the constants file called

    # this will hold all of the constants
    frameWidth = 1600
    frameHeight = 900
    

    Here is the code that uses the constants

    public class SimpleGuiAnimation {
    
        int frameWidth;
        int frameHeight;
    
    
        public SimpleGuiAnimation() {
            Properties properties = new Properties();
    
            try {
                File file = new File("src/main/resources/dataDirectory/gui_constants.properties");
                FileInputStream fileInputStream = new FileInputStream(file);
                properties.load(fileInputStream);
            }
            catch (FileNotFoundException fileNotFoundException) {
                System.out.println("Could not find the properties file" + fileNotFoundException);
            }
            catch (Exception exception) {
                System.out.println("Could not load properties file" + exception.toString());
            }
    
    
            this.frameWidth = Integer.parseInt(properties.getProperty("frameWidth"));
            this.frameHeight = Integer.parseInt(properties.getProperty("frameHeight"));
        }
    

提交回复
热议问题