在这种情况下,“ ParameterizedType#getActualTypeArguments”将返回一个包含多个元素的数组

时间:2019-11-22 10:03:49

标签: java

我试图在通用类型中获取类类型,并且下面的代码起作用:

PreparedStatement reader = null;
PreparedStatement writer = null;
ResultSet rs = null;
try {

reader = sourceConnection.prepareStatement("select....");
writer = destinationConnection.prepareStatement("insert into...");
rs = reader.executeQuery();
int chunksize = 10000;  // this is you batch size, depends on your system
int counter = 0;
while ( rs.next() {
 writer.set....  // do for every field to insert the corresponding set 

 writer.addBatch();
 if ( counter++ % chunksize == 0  ) {
    int rowsWritten = writer.executeBatch();
    System.out.println("wrote " + counter + " rows");  // probably a simple message to see a progress
 }
}
// when finished, do not forget to flush the rest of the batch job
writer.executeBatch();
} catch (SQLException sqlex ) {
// an Errormessage to your gusto
  System.out.println("SQLException: " + sqlex.getMessage());
} finally {
  try {
    if ( rs != null ) rs.close(); 
    if ( reader != null ) reader.close();
    if ( writer != null ) writer.close();
    // probably you want to clsoe the connections as well
  } catch (SQLException e ) {
    System.out.println("Exception while closing " + e.getMessage());
  }
 }

所以,我学到了关于@Test public void test3() throws NoSuchFieldException { Class<?> clazz = (Class<?>) ((ParameterizedType)Role.class.getDeclaredField("users") .getGenericType()).getActualTypeArguments()[0]; assert clazz.equals(User.class) : "error!"; } static class Role { public List<User> users; } static class User { } 的一些知识。

我想知道ParameterizedType在哪种情况下返回一个包含多个元素的数组。我尝试了很多情况,但是所有结果都是大小为1的数组。

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

如果您有多个通用参数(例如在Map中),它将返回一个以上元素的数组。

示例:

@Test
public void exampleTest() {
    Map<Integer, String> myMap = new HashMap<>();
    ParameterizedType type = (ParameterizedType) myMap.getClass().getGenericSuperclass();
    System.out.println("Array of actual types : " + Arrays.toString(type.getActualTypeArguments()));
}

输出为:

  

实际类型数组:[K,V]