Java不确定类型

时间:2016-10-17 23:40:05

标签: java class mutable typename

我的公司有一个应用程序服务器,它以自己的定制XTML语法接收指令集。由于这是有限的,因此有一个特殊的“drop to Java”命令将参数发送到JVM(1.6.0_39)。参数仅作为“输入”或“输入/输出”传递,其中特殊的“输入/输出”变量是用于此平台的可变数据库。

以前,接收外部配置的唯一方法是使用不同的特殊命令从XTML文件中读取。由于不值得深入研究的原因,这种配置方法很难扩展,所以我正在研究用Java做这个的方法。

此配置的语法是(String,T)的两元组,其中String是XTML文件中的属性名称,T是应用程序服务器将属性值分配给的输入/输出可变。

我正在尝试尽可能无缝地进行此转换,而不必在应用程序服务器中进行恼人的字符串解析。

我已经有了一个功能

public String[] get(String ... keys)

从应用服务器的密钥中检索值,但我真正需要的是一个函数

public static void get(T ... args)

接受两元组。但是,请注意它必须是静态才能从应用程序服务器调用,我的理解是 T 不能在静态上下文中使用。

我不知道如何以不需要(至少)两个步骤的方式处理这个问题,并且无法循环应用程序服务器中的参数。

我知道我在这里遇到了一系列严格的限制,所以如果答案是“你必须搞砸一些东西”,那很好 - 我只是想要了解另一种方式。

- 编辑 -

编辑更具体的示例。

配置是一组键值对,可以在数据库或文件中。 获取功能是:

public JSONObject get(String ... keys) throws ClassNotFoundException, SQLException, KeyNotFoundException, FileNotFoundException, IOException {
JSONObject response = new JSONObject();
if(this.isDatabase) {
  for(int i=0;i<keys.length;i++){
    PreparedStatement statement = this.prepare("SELECT value FROM "+this.databaseSchema+"."+this.settingsTableName+" WHERE key = ? LIMIT 1");
    statement.setString(1, keys[i]);
    ResultSet results = statement.executeQuery();
    boolean found = false;
    while(results.next()){
      String value = results.getString("value");
      value = value.replace("\"","");
      response.put(keys[i], value);
      found = true;
    }
    if(!found){
      throw new KeyNotFoundException(keys[i]);
    }
  }   
} else if (this.isFile) {
  boolean[] found = new boolean[keys.length];
  BufferedReader br = new BufferedReader(new FileReader(this.settingsFile));
  String line;
  while((line = br.readLine()) != null ){
    String key;
    String value;
    for(int i=0;i<line.length();i++){
      if(line.charAt(i) == '='){
        key = line.substring(0,i);
        value = line.substring(i+1,line.length());
        if(indexOfString(keys,key) != -1){
          value = value.replace("\"","");
          found[indexOfString(keys,key)] = true;
          response.put(key,value);
          if(allFound(found)==-1){
            return response;
          }
        }
        break;
      }
    }
  }
  if(allFound(found)!=-1){
    throw new KeyNotFoundException(keys[allFound(found)]);
  }
}
return response;

如果我按照自己的方式行事,那就好像......

// ConfigurationReader.java
public class ConfigurationReader{
   public ConfigurationReader( ... ){}
   public static JSONObject get(String key){
       // Get the key
   }
}
// ConfigurationInterface.java
public static void get(T ... args){
   ConfigurationReader cfgReader = new ConfigurationReader( ... );
   for(var i=0;i<args.length;i+=2){
       in = args[i];
       out = args[i+1];
       out = cfgReader.get(in);
   }
}

2 个答案:

答案 0 :(得分:3)

可以在静态上下文中使用泛型类型。你的问题有点模糊/不清楚你打算怎么做,但请考虑下面的例子:

public class Example {

    public static void main(String[] args) {
        Type t1 = new Type("foo");
        Type t2 = new Type("bar");
        Type t3 = new Type("baz");

        Printer.<Type> printNames(t1, t2, t3);
    }

    public static class Printer {
        @SafeVarargs
        public static <T extends Type> void printNames(T... objs) {
            for (T obj : objs) {
                System.out.println(obj);
            }
        }
    }

    public static class Type {
        private final String name;

        public Type(String name) {
            this.name = name;
        }

        @Override
        public final String toString() {
            return name;
        }
    }
}

Printer.<Type> printNames(t1, t2, t3)printNames方法进行静态引用,使用Type泛型类型进行参数化。

请注意,此类型安全的。尝试将不同类型的对象传递给该参数化方法将在编译时失败(假设该类型在该点已知不同):

 Example.java:8: error: method printNames in class Printer cannot be applied to given types;
        Printer.<Type> printNames(t1, t2, t3, "test");
               ^
  required: T[]
  found: Type,Type,Type,String
  reason: varargs mismatch; String cannot be converted to Type
  where T is a type-variable:
    T extends Type declared in method <T>printNames(T...)

修改

根据您的评论,问题不是您尝试使用泛型类型作为您的方法参数(无论如何,在Java语义中使用泛型一词) ;您只需查找String和您的自定义类型继承的任何非特定的父类。只有一个这样的课程:Object

如果您有任何灵活性,我强烈建议重新考虑您的设计,因为这会导致API设计不佳。但是,您可以使用Object... objs接受任意数量的任意类型对象。

例如:

public class Example {

    public static void main(String[] args) {
        Printer.printNames("a", "b", new Type("foo"), new Type("bar"));
    }

    public static class Printer {
        public static void printNames(Object... objs) {
            for (Object obj : objs) {
                if (obj instanceof String) {
                    System.out.println(((String) obj).toUpperCase());
                }
                else if (obj instanceof Type) {
                    System.out.println(obj);
                }
            }
        }
    }

    public static class Type {
        private final String name;
        public Type(String name) { this.name = name; }
        public final String toString() { return name; }
    }
}

答案 1 :(得分:0)

根据@nbrooks的工作,我找到了一个解决方案。我做了一个临时的 MutableString (将被库提供的类所取代)。

public static class MutableString {
  public String value;
  public MutableString(){}
}  

// One for every mutable type
public static void Pair(String key, MutableString mutable, ApplicationConfiguration appConfig) throws Exception{
  mutable.value = appConfig.get(key).toString();
}

public static void Retrieve(Object ... args) throws Exception {
  ApplicationConfiguration appConfig = new ApplicationConfiguration( ##args## );
  for(int i=0;i<args.length;i+=2){
    if(args[i+1].getClass().equals(new MutableString().getClass())){
      ApplicationConfiguration.Pair( (String) args[i], (MutableString) args[i+1], appConfig);
    } // One for every mutable type
  }   
}