Java .properties 文件作为强类型类 [英] Java .properties files as strongly typed classes

查看:27
本文介绍了Java .properties 文件作为强类型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将属性文件作为强类型类获取?我想有代码生成器,但用注释来做会更酷.

Is there way to get properties files as strongly typed classes? I guess there are code generators but doing it with annotations would be much cooler.

我的意思是;

foo.properties file
keyFoo = valuefoo
keyBar = valuebar

也许与

@properties(file="foo.properties")
class foo { }

变成

class foo {
  String getKeyFoo() { }
  String getKeyBar() { }
}

如果不是,我应该为此启动一个开源项目吗?

if not shall I start an open source project for that?

问题的补充;

认为我们有一个 foo.properties 文件,可以说超过 10 个条目;并认为它是用作一个简单的配置文件.我认为,这个配置条目应该作为一个配置类提供,与设计的其他部分相关的 getXXX 方法.然后系统的其余部分通过提供的类访问配置而不是处理键名,并且不需要打扰配置的来源.然后,当您测试调用者并且对文件系统的依赖消失时,您可以用模拟替换此类.另一方面,它真的很好以强类型方式获取所有条目.

Think we have a foo.properties file with let say more than 10 entries; and think it is used as a simple configuration file. What I believe is that this configuration entries should be provided as a configuration class with related getXXX methods to other parts of the design. Then rest of the system accesses the configuration via provided class instead of dealing with key names and don't need to bother where configuration comes. Then you can replace this class with a mock when you are testing callers and dependency to file system goes away. On the other hand it is really nice to get all entries in a strongly typed fashion.

所以这个问题是幕后的代码生成问题,与运行时无关.但是使用外部内容而不是注释生成代码对我来说似乎并不好.虽然我对注解不是很熟悉,但我想这是可以实现的(但我会记住注解不能像麦克道尔点那样生成类)

So this issue is a code generation issue behind the scenes, it is nothing related to runtime. But code generation with an external something instead of annotations didn't seemed nice to me. Although I am not very much familiar with annotations, I guess this could be achieved (but I'll keep in mind that annotations can not generate classes as McDowell points)

推荐答案

有一个 有点类似的项目,用于将配置作为静态类型文件.它需要声明一个接口,但它填充了实现本身:

There is a somewhat similar project for doing configuration as statically typed files. It requires to declare an interface, but it fills in the implementation itself:

public interface AppConfig extends Config {
    long getTimeout ();
    URL getURL ();
    Class getHandlerClass ();
}

这篇关于Java .properties 文件作为强类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆