Java - How do I use a class file?

依然范特西╮ 提交于 2020-01-01 10:03:09

问题


I'm new to Java and am wondering about how to import class files into netbeans and use it.

I understand that a class file is machine-readable byte code but I don't care what's going on under the hood. I'd just like to import it into my current project and have it recognize it so I can use the class.

Also, the class file is embedded within a JAR file. I imported the JAR file into my libraries folder/tab in the projects window but I don't know how to get my project to recognize the class. It says "cannot find symbol" whenever I try to instantiate an object.


回答1:


You have to import by calling the name of source package . ie import hello.Car; . In your case you are trying to call import on JAR folder name which leads to an error "cannot find symbol" .

Let me try to give an example for better understandability

  • Consider this simple Vehicle application which has Car class and Test Car class

  • Convert it into jar and add it into another project called ImportVehicleJar

    alt text http://i46.tinypic.com/qxmlxt.png

    • In order to instantiate the Car class in Main.Java file add the following as shown in figure

    Hope this helps !!




回答2:


In Netbeans (version 5.5.1), you can add a jar file to a project by right clicking the project name, and choosing Properties, then Libraries (from Categories), and there is an "Add JAR/Folder" button, which can be used for adding it to the compile-time and/or run-time classpath. Adding it to the Compile-time Libraries is well enough, because it will automatically added to the run-time through its "Classpath for Compiling Sources" entry.




回答3:


You either need to specify the full package pathname to the class. e.g

com.foobar.acme.Clobula myBigClobula = new com.foobar.acme.Clobula();

or use an import statement

import com.foobar.acme.Clobula
...
.
 Clobula myBigClobula = new Clobula();



回答4:


Also, class files aren't machine-readable / binary in the sense that compiled c files are. Open a class file with your text editor and you will see that it is in fact a list of text instructions. The Java Virtual Machine looks at these class files and interprets them, executing the resulting instructions.



来源:https://stackoverflow.com/questions/1983513/java-how-do-i-use-a-class-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!