如何在java中替换/转换/扩展String

时间:2014-01-28 04:43:19

标签: java hashmap switch-statement

我有一个方法将给定的字符串映射到另一个字符串,就好像方法的输入是“RS256”它将返回“SHA256WithRSA”等等。我的方法如下:

public String getAlgorithm(String alg) {

    // The internal crypto provider uses different alg names

        switch(alg) {
            case "RSA256" : return "SHA256withRSA";
            case "SHA384" : return "SHA384withRSA";
            case "SHA512" : return "SHA512withRSA";
        }
        throw new Exception("Not supported");

}

还有其他方法吗(我不想使用 MAP )。我想看看是否有任何设计模式或任何OOP概念来做到这一点。

5 个答案:

答案 0 :(得分:1)

使用真实地图,我的意思是java.util.Map保持键值对ex。 Map<Key,Value>

Map<String,String> map= new HashMap<String,String>();
map.add("RSA256","SHA256withRSA");
map.add("SHA384","SHA384withRSA");
map.add("SHA512","SHA512withRSA");
...

public String getAlgorithm(String alg) {
     return map.get(alg);
}

答案 1 :(得分:1)

你实际上是在这里写了一个Facade Pattern,我想你正在包装某种类型的库。 switch-case语句应该没问题。 使用map会引入开销,所以最好不要使用它。

答案 2 :(得分:0)

您可以使用if-else检查alg等于您的情况,并返回与此类似的值。但目前的方式与此非常相似。

为什么你不能使用Map?这是更好的方式。

Map<String,String> algoMap=new HashMap<>(String,String);

现在你可以放algoMap.put("algoName","Value")

答案 3 :(得分:0)

使用HashMap

HashMap<String, String> newMap = new HashMap<String, String>();
newMap.put("RSA256", "SHA256withRSA");
newMap.put("SHA384", "SHA384withRSA");
newMap.put("SHA512", "SHA512withRSA");
String value = (String) newMap.get("RS256");

答案 4 :(得分:0)

您也可以使用枚举类型,但无论哪种方式,您都必须使用不带映射的switch语句。

enum Algorithm {
   RSA256,
   SHA384,
   SHA512;

   public String name(String pValue) throws Exception {
      switch(this) {
         case RSA256:
         return "SHA256withRSA";
         case SHA384:
         return "SHA384withRSA";
         case SHA512:
         return "SHA512withRSA";
         default:
         throw new Exception("Not supported");
   }
 }

}