簡體   English   中英

使用通過反射創建的對象的問題

[英]Issue with using an object created via reflection

我正在嘗試編寫一個程序,該程序可用於向一組訂閱者發送消息。 用於傳遞消息的訂閱者和技術並不重要。 消息類型由 XML 模式定義並作為 Java API 實現。 所有消息類型都擴展了一個抽象超類型。 API 定義了靜態方法以允許在 XML 和 Java 之間進行轉換,反之亦然( fromXML()toXML() )。

我在執行此操作時遇到困難。 我在下面包含了我試圖開始工作的代碼示例。 它沒有按照編寫的方式編譯。 抽象超類型是MessageType類,我的計划是傳入“真實”消息類型的名稱,並讓此代碼創建必要的對象來執行發送指定子類型的消息所需的操作。

public class Writer {

  public static void runExample(String[] args) throws Exception {
    UUID serviceID = UUID.fromString(args[1]);

    ServiceBus bus = ServiceBus.getServiceBus();
    bus.init(serviceID);

    // The intention is to pass the message type name so that this code can be used for any
    // "message" type.
    String msgName = args[0];

    // Get the message type class from the passed name.
    Class<? extends MessageType> msgClass = (Class<? extends MessageType>) Class.forName(msgName);

    // Create a writer for the specified message type.
    MessageWriter<? extends MessageType> writer = bus.createWriter(msgName, msgClass);

    // Read in some XML content from a file.
    String xml = loadMsg(args[2]);

    // Want to do something like this:
    msgClass object = msgClass.fromXML(xml);
    // Of course, this does not compile. Is there a way to do this?

    // Create a java object of the message type from the XML read in.
    MessageType object = MessageType.fromXML(xml);

    // With the line above the statement below fails to compile with the error:
    //   The method write(capture#4-of ? extends MessageType) in the type
    //   MessageWriter<capture#4-of ? extends MessageType> is not applicable for
    //   the arguments (MessageType)

    writer.write(object);
  }

  private static String loadMsg(String fileName) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)));
    String line = null;
    StringBuilder sb = new StringBuilder();

    do {
    line = reader.readLine();
    if (line != null)
      sb.append(line);
    } while (line != null);

    reader.close();
    return sb.toString();
  }

}

有誰知道是否可以做我上面描述的事情?

由於您的WriterMessageWriter<? extends MessageType> MessageWriter<? extends MessageType> ,這意味着它可以是任何MessageWriter ,它利用一個子類MessageType 所以實際的實例可能是MessageWriter<MySuperMessageType> 由於編譯器無法確認您的MessageType實例為MySuperMessageType ,因此編譯器將失敗。

如果作者是MessageWriter<MessageType>MessageWritier<? super MessageType> MessageWritier<? super MessageType>它會起作用。 另一種選擇是創建一個通用方法......

private <T extends MessageType> myMethod(Class<T> type){
   MessageWriter<T> writer = bus.createWriter(msgName, msgClass);
   String xml = loadMsg(args[2]);
   // you could use reflection to get the public static methods from the class instance
   // msgClass object = msgClass.fromXML(xml);
   T object = (T) MessageType.fromXML(xml);
   writer.write(object);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM