1

このような単純なテキストファイルを使用します

BMG-P   (someLongComplicatedExpression)(.*P)
BMG T   (someLongComplicatedExpression)(.*[Tt])
BMG MPA (someLongComplicatedExpression)(.*MPA)

アプリケーションを構成するには ( を使用した単純なインポートbufferedReader.readLine().split("\t"))。私を悩ませているのは冗長性です。

次のような解決策を考えています。

%s=(someLongComplicatedExpression)
BMG-P   %s(.*P)
BMG T   %s(.*[Tt])
BMG MPA %s(.*MPA)

ここで、変数 (%s など) の値を読み取り、インポート後に文字列内のそれらの出現箇所を置き換えます。

私の質問は次のとおりです。

  • どのような代替アプローチを知っていますか?
  • コードで変数の置換を実装する簡単な方法は何ですか?
  • そのようなプロパティ ファイルをサポートするフレームワークを教えてもらえますか?
4

1 に答える 1

1

Properties私はJavaクラスにこの単純な拡張を書きました:

import java.io.Serializable;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Allows properties to contain expansions of the form ${propertyName}. This
 * class makes no attempt to detect circular references, so be careful.
 */
public class ExpandingProperties extends Properties implements PropertySource {

    private static final long serialVersionUID = 259782782423517925L;
    private final Expander expander = new Expander();

    @Override
    public String getProperty(String key) {
        return expander.expand(super.getProperty(key), this);
    }
}

class Expander implements Serializable {

    private static final long serialVersionUID = -2229337918353092460L;
    private final Pattern pattern = Pattern.compile("\\$\\{([^}]+)\\}");

    /**
     * Expands variables of the form "${variableName}" within the
     * specified string, using the property source to lookup the
     * relevant value.
     */
    public String expand(final String s, final PropertySource propertySource) {
        if (s == null) {
            return null;
        }
        final StringBuffer sb = new StringBuffer();
        final Matcher matcher = pattern.matcher(s);
        while (matcher.find()) {
            final String variableName = matcher.group(1);
            final String value = propertySource.getProperty(variableName);
            if (value == null) {
                throw new RuntimeException("No property found for: " + variableName);
            }
            matcher.appendReplacement(sb, value.replace("$", "\\$"));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}

interface PropertySource {

    String getProperty(String key);
}

使用例:

public static void main(String[] args) {
    Properties properties = new ExpandingProperties();
    properties.put("myVar", "myLongExpression");
    properties.put("foo", "${myVar}_1");
    properties.put("bar", "${foo}_abc");

    System.out.println(properties.getProperty("bar"));
}

プリント:

myLongExpression_1_abc

そのExpandingProperties拡張であるように、プロパティファイルから値をロードするためPropertiesのすべてのメソッドを継承します。load...()

別の方法は、上記のコードと同様のことを行うEPropertiesですが、さらに進んで、プロパティファイルなどをネストすることができます。必要なものに対してはやり過ぎだと思いました。

于 2012-08-10T12:38:41.533 に答える