Java在HashMap中存储连接。

huangapple go评论84阅读模式
英文:

Java Store a Connection in a HashMap

问题

以下是翻译好的部分:

我原本希望构建一个通用的HashMap,用于存储一些东西,其中之一就是连接对象(Connection Object)。这是一个简化的示例:

初始化函数:

public Map<Object, Object> genObjectInit() {
   Map<Object, Object> genObject = new HashMap<Object, Object>();
}

添加连接对象(以连接为例):

public Map<Object, Object> genObjectConnect(Map<Object, Object> genObject) throws Exception {
   Connection PgSQL;
   try {
      Class.forName("org.postgresql.Driver");
      PgSQL = DriverManager.getConnection(/* 这里填写连接信息 */);
   } catch(Exception log) {
      throw new Exception("连接失败");
   }
   genObject.put("PgSQL", PgSQL);
   return genObject;
}

测试是否正常工作:

public void genObjectTest(Map<Object, Object> genObject) {
   genObject.put("Yes", "Yes");
   System.out.println(genObject.get("PgSQL").getClass().getName());
   genObject.get("PgSQL").close();
}

将连接添加到HashMap中似乎是有效的,genObject.get("PgSQL").getClass().getName() 的输出为 org.postgresql.jdbc.PgConnection,我认为这意味着它仍然是一个连接对象,但是调用 genObject.get("PgSQL").close(); 时会崩溃,报错如下:

/yes/yes/yes.java:45: error: cannot find symbol
   genObject.get("PgSQL").close();
                     ^

我显然对某些地方存在误解。我如何使用通用存储的连接(或等效但同样独特的对象)的功能?
英文:

I was hoping to build a generic HashMap to use for storing a few things, one of them being a Connection Object. This is a simplified example :

Function to initialize

public Map&lt;Object, Object&gt; genObjectInit() {

   Map&lt;Object, Object&gt; genObject = new HashMap&lt;Object, Object&gt;();

}

Add a connection object (as an example)

public Map&lt;Object, Object&gt; genObjectConnect(Map&lt;Object, Object&gt; genObject) throws Exception {

   Connection PgSQL;

   try {
      Class.forName(&quot;org.postgresql.Driver&quot;);
      PgSQL = DriverManager.getConnection ( /* yes */ );
   } catch(Exception log) {
      throw new Exception(&quot;failed to connect&quot;);
   }

   genObject.put(&quot;PgSQL&quot;, PgSQL);

   return genObject;

}

Test if it's working at all

public void genObjectTest(Map&lt;Object, Object&gt; genObject) {

   genObject.put(&quot;Yes&quot;, &quot;Yes&quot;);

   System.out.println(genObject.get(&quot;PgSQL&quot;).getClass().getName());
   genObject.get(&quot;PgSQL&quot;).close();


}

Adding the Connection to the HashMap seems to be working, the output from genObject.get(&quot;PgSQL&quot;).getClass().getName() is giving me org.postgresql.jdbc.PgConnection which I assume means it is still a Connection object but calling genObject.get(&quot;PgSQL&quot;).close(); crashes with

/yes/yes/yes.java:45: error: cannot find symbol
   genObject.get(&quot;PgSQL&quot;).close();
                         ^

I've clearly misunderstood something here. How can I use the functionality of a generically stored Connection (or equivalent but equally unique object)?

答案1

得分: 2

使用 Map<Object, Object> 可以让您访问在 Object 类中声明的方法,因为当您从映射中检索对象时,

public void genObjectTest(Map<Object, Object> genObject) {

   genObject.put("Yes", "Yes");

   System.out.println(genObject.get("PgSQL").getClass().getName());
   genObject.get("PgSQL").close();


}

然后 genObject.get("PgSQL") 的结果存储在 Object 类的实例中。

根据您的用例,您可以尝试使用具有特定类型的 Java 泛型,并将您的 Map 声明为 Map<Object, Connection>,如下所示:

public void genObjectTest(Map<Object, Connection> genObject) {

    genObject.put("Yes", connectionInstance);

    System.out.println(genObject.get("PgSQL").getClass().getName());
    Connection pgSQL = genObject.get("PgSQL");
    try {
        pgSQL.close();
    } catch (SQLException throwables) {
        throwables.printStackTrace();
    }
}

这给您带来了许多优势,其中之一是编译时类型检查,或者您最终可以在检索对象时进行类型转换,如下所示:

public void genObjectTest(Map<Object, Object> genObject) {

    genObject.put("Yes", "Yes");

    System.out.println(genObject.get("PgSQL").getClass().getName());
    Object connectionAsObject = genObject.get("PgSQL");
    if (connectionAsObject instanceof Connection) {
        Connection pgSQL = (Connection) connectionAsObject;
        try {
            pgSQL.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

然而,这是较不推荐的解决方案。使用第一个解决方案,即具有特定类型的 Java 泛型,另一个优点是您不必进行此类型转换。

英文:

Using Map&lt;Object, Object&gt; gives you access to the methods declared in Object class, because when you retrieve an object from the map

public void genObjectTest(Map&lt;Object, Object&gt; genObject) {

   genObject.put(&quot;Yes&quot;, &quot;Yes&quot;);

   System.out.println(genObject.get(&quot;PgSQL&quot;).getClass().getName());
   genObject.get(&quot;PgSQL&quot;).close();


}

then result of the genObject.get(&quot;PgSQL&quot;) is stored in an instance of the Object class.

Depending on your use case you could either try to use Java Generics with the specific type and declare your Map as Map&lt;Object, Connection&gt; like this:

    public void genObjectTest(Map&lt;Object, Connection&gt; genObject) {

        genObject.put(&quot;Yes&quot;, connectionInstance);

        System.out.println(genObject.get(&quot;PgSQL&quot;).getClass().getName());
        Connection pgSQL = genObject.get(&quot;PgSQL&quot;);
        try {
            pgSQL.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

which gives you many advantages, one of them is compile-time type checks, or you could eventually do type casting when retrieving an Object like:

public void genObjectTest(Map&lt;Object, Object&gt; genObject) {

    genObject.put(&quot;Yes&quot;, &quot;Yes&quot;);

    System.out.println(genObject.get(&quot;PgSQL&quot;).getClass().getName());
    Object connectionAsObject = genObject.get(&quot;PgSQL&quot;);
    if (connectionAsObject instanceof Connection) {
        Connection pgSQL = (Connection) connectionAsObject;
        try {
            pgSQL.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}

Which however is less preferred solution. With the first solution, i.e. java generics with the specific type, another advantage is that you don't have to do this type casting.

huangapple
  • 本文由 发表于 2020年9月12日 16:47:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/63858540.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定