【问题标题】:How do I recompile with -Xlint? Jgrasp如何使用 -Xlint 重新编译?掌握
【发布时间】:2014-05-17 11:41:53
【问题描述】:

我的程序似乎按我的喜好运行。但是,当我编译它时,我会收到以下消息:

Note: Program.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

如何使用 -Xlint 识别不安全的操作,或者程序中的什么导致了此消息?我认为这与我的 Node 类有关..?

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import javax.swing.JOptionPane;

/**
 * An application that reads from a file, enters/deletes in queue and writes output to the file
 */
public class Program {

/**
 * Driver code to test class
 * 
 * @param arguments
 *            Commandline arguments. 1st argument is input file and 2nd argument is output file
 * @throws IOException 
 */
   public static void main(String[] arguments) throws IOException {


    //Queue Object
      MyQueue<String> queue= (new MyQueue<String>());

      String name;
      //reading file
      read(queue,arguments[0]);

      String[] array = { "Offer Person", "Poll Person", "Peek person","Display Queue", "Exit Program"};
      int choice = 0;

        // display loop   
      while (choice != array.length-1) {
         choice = JOptionPane.showOptionDialog(null, // put in center of screen
                  "Press a Button", // message to user
                  "Queue(Line) of People", // title of window
                  JOptionPane.YES_NO_CANCEL_OPTION, // type of option
                  JOptionPane.QUESTION_MESSAGE, // type of message
                  null, // icon
                  array, // array of strings
                  array[array.length - 1]); // default choice (last one)


         if(choice==0)
         {
            //inserting the new name in queue
            name=JOptionPane.showInputDialog(null,"Enter Person's name","Input");
            queue.offer(name);

         }
         else if(choice==1){

                //Display and remove the name which is at front of line
            JOptionPane.showMessageDialog(null, queue.poll() + " is next in line");

         }

         else if(choice==2){

                //Display name which is at front of line
            JOptionPane.showMessageDialog(null, queue.peek() + " is front of the line");

         }

         else if(choice==3){
                //Dispay all the list
            JOptionPane.showMessageDialog(null, queue.toString());


         }
               //JOptionPane.showMessageDialog(null, "Your pressed button #" + choice);
      }
    //calling writing function
      write(queue, arguments[1]);


   }// end of main()

   /**
     * Reads a file
     * @param queue 
     * @param file_name name of file
     */
   public static void read(QueueInterface<String> queue, String file_name) throws IOException{

      try
      {
         String name;
            //creating a buffer reader to read
         BufferedReader br= new BufferedReader(new FileReader(file_name));
         while((name=br.readLine()) != null){
              //putting in the queue
            queue.offer(name);
         }
              //closing buffer reader
         br.close();
      }
      catch(Exception ex)
      {
         System.err.println(ex.getMessage());
      }

   }

   /**
    * Writes the contents of LinkedQueue to the output file at the ned of program
    * @param queue QueueInterface methods
    * @param file_name name of file
    */
   public static void write(QueueInterface<String> queue, String file_name) throws IOException{
      try
      {
         String name;
      //creating a buffer writer to write
         BufferedWriter bw= new BufferedWriter(new FileWriter(file_name));
         while((name=queue.poll()) != null){
          //writin in file
            bw.write(name);
            bw.newLine();

         }
          //closing buffer
         bw.close();
      }
      catch(Exception ex)
      {
         System.err.println(ex.getMessage());
      }
   }



}// end of class

/**
* Interface to be implemented by LinkedQueue
*/
interface QueueInterface<String> 
{
   public boolean empty();
   public boolean offer(String element);
   public String poll();
   public String peek();
}

class Node<String>
{
   private String data;
   private Node nextNode;
   public Node(String dataObject, Node nextNodeObject)
   {
      this.data=dataObject;
      this.nextNode=nextNodeObject;
   }

    /**
    * Gets the next node
    * @return next node
    */
   public Node getNext()
   {
      return nextNode;
   }

    /**
    * Sets the next node of the current node
    * @param nextNodeObject next node to be set as next to the current node
    */
   public void setNext(Node nextNodeObject)
   {
      nextNode=nextNodeObject;
   }

    /**
    * Sets data of the current node
    * @param dataObject data to be inserted in new node
    */
   public void setData(String dataObject)
   {
      this.data=dataObject;
   }

    /**
    * Gets data of the current node
    * @return data of the node
    */
   public String getData()
   {
      return this.data;
   }
}

class LinkedQueue implements QueueInterface<String>
{
   protected Node<String> lastNode=null;

   LinkedQueue() {
   }

    /**
    * Checks if the queue is empty
    * @return true if empty, false if not empty
    */
   public boolean empty() {
      if(lastNode==null)
      {
         return true;
      }
      else
         return false;
   }

    /**
    * Inserts new node in the queue
    * @param element data to be inserted in new node
    * @return true on success
    */
   public boolean offer(String element) 
   {
      Node<String> newLastNode = new Node<String>(element,null);

        //If the LinkedQueue is empty, add the node to the last and point next to itself
      if(empty())
      {
         newLastNode.setNext(newLastNode);
      }
      else
      {
            // Adding to the front of queue and updating next of the last node
         newLastNode.setNext(lastNode.getNext());
         lastNode.setNext(newLastNode);
      }
      lastNode=newLastNode;
      return true;
   }

    /**
    * Removes the first node and returns it
    * @return data at first node
    */
   public String poll() 
   {
        // If queue is empty then return null
      if(empty())
         return null;
      else
      {
         Node<String> frontNode = lastNode.getNext();

            //Check if there will be no node left after polling this one
         if (frontNode == lastNode) 
         {
            lastNode = null;
         }
         else //Remove the first node and update next of the last node
         {
            lastNode.setNext(frontNode.getNext());
         }
         return frontNode.getData();
      }
   }

    /**
    * Returns data of the first node without removing it from the queue
    * @return data at first node
    */
   public String peek() 
   {
      if (empty())
      {
         return null;
      }
      else
      {
         Node<String> frontNode = lastNode.getNext();
         return frontNode.getData();
      }
   }
}

class MyQueue<String> extends LinkedQueue{

   /**
    * Constructor
    * 
    */
   public MyQueue() 
   {
      super();      
   }

   /**
    * Returns a string representation of the object
    * 
    * @return a name on different lines
    */
   public java.lang.String toString() 
   {
        // create a variable to return
      java.lang.String toReturn = "";

        // Traversing the list
      Node<String> frontNode = lastNode.getNext();

      if(empty())    //If queue is  empty
         return "";
      else if(frontNode==lastNode)    //If only one elemtn
      {
         return frontNode.getData().toString();
      }
      else    //More than one element in the queue
      {
         while(frontNode != lastNode)
         {
            toReturn=toReturn+frontNode.getData()+"\n";
            frontNode=frontNode.getNext();
         }
         toReturn= toReturn+frontNode.getData()+"\n";    //Appending data of last node because it will be missed in the loop
      }
      return toReturn;
   }
}

【问题讨论】:

  • 我不知道这是否是导致您出现该错误的原因,但在您的 QueueInterfaceNodeMyQueue 声明中,您实际上使用了 String 这个词作为一个类型参数。这令人难以置信的混乱,因为它实际上会隐藏String 类的使用,这就是为什么你必须在MyQueue 类中写几次java.lang.String。我可以恭敬地建议您在这些声明中将String 更改为T 吗?其他人都是这样做的。

标签: java compiler-construction compiler-errors


【解决方案1】:

在build.gradle中添加

allprojects {
gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked" << "-Xlint:deprecation"
    }
}

}

【讨论】:

    【解决方案2】:

    在 jGrasp 中,该选项位于“设置”菜单项下。转到 Settings-> File/Workspace/Project(选择适用于您的),然后在 Compiler 标签上,选择 Flags/Args 选项卡,然后单击 Compile 旁边的框并在文本中输入 -Xlint:unchecked盒子。单击应用,在您的下一个构建中,您将收到有关未选中内容的消息。

    正如其他人指出的那样,之所以会引发此警告,是因为您使用的是泛型类的原始形式,而不是为其提供类型参数。 -Xlint:unchecked 将显示您在代码中的哪个位置执行此操作。

    【讨论】:

      【解决方案3】:

      假设使用“String”作为类型参数不是导致实际消息的原因(或者即使确实如此),我快速浏览一下:

      Node<String> frontNode = lastNode.getNext();
      

      但是 getNext() 返回的是 Node 而不是 Node (应该是 Node 一旦你修复了类型参数名称)。

      在 jGRASP 中,您可以使用“设置”>“编译器设置”>“工作区”(或“项目...”或“文件”)为各种命令添加标志。只需在 Java 语言的“编译”命令中为“标志或参数”添加“-Xlint”即可。

      【讨论】:

        【解决方案4】:

        如果您在命令行上编译(即javac Program.java),您只需添加-Xlint:unchecked 参数即可让它为您打印出警告:

        javac Program.java -Xlint:unchecked

        这应该会向您指出问题所在。但是,正如@DavidWallace 在评论中提到的那样,您应该考虑修改您对泛型的使用,使其更加清晰——即使不使用-Xlint 参数,这也可能向您揭示您的问题。

        如果你的类真的应该只处理Strings,那么你根本不需要包含类型参数(现在,在你的代码中,&lt;String&gt; 是一个类型参数,代表你传递的类型在你使用这个类时——它并不意味着它必须是java.lang.String——这就是为什么@DavidWallace 建议你改用T)。 Here's 一个很好的教程,如果你想复习如何使用泛型。

        【讨论】:

          猜你喜欢
          • 2018-05-24
          • 1970-01-01
          • 1970-01-01
          • 2019-05-31
          • 2015-10-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-07-29
          相关资源
          最近更新 更多