How Java Import Works - Stack Overflow PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

5/19/2017 HowjavaimportworksStackOverflow

xDismiss

JointheStackOverflowCommunity

Stack Overflow is a community of 7.1 million


programmers, just like you, helping each other.
Join them it only takes a minute:

Signup

Howjavaimportworks

Iwouldliketoknowhowthe import works.

I'maskingthis,becauseIhavethefollowing imports inmyproject

importstaticcom.googlecode.javacv.jna.highgui.cvCreateCameraCapture;
importstaticcom.googlecode.javacv.jna.highgui.cvGrabFrame;
importstaticcom.googlecode.javacv.jna.highgui.cvReleaseCapture;
importcom.googlecode.javacv.CanvasFrame;
importcom.googlecode.javacv.FrameGrabber;
importcom.colorfulwolf.webcamapplet.gui.ImagePanel;
importcom.googlecode.javacv.OpenCVFrameGrabber;
importcom.googlecode.javacv.jna.cxcore.IplImage;

Idon'thaveinmyprojectthese package so,howthiswillbeimported?

IfIcreatea jar filewithallmyclasses,myserverwherewillhostthis jar file,hastobefreeinternetaccesstoget


these package ?

Igotsomeprobleminmy Applet thathasthese import andI'maskingthisquestion,tounderstandifcanbeainternet


rule.

UPDATE

<appletcode="com.colorfulwolf.webcamapplet.WebcamApplet"
archive="http://san.redenetimoveis.com/teste.jar,http://san.redenetimoveis.com/core.jar,
http://san.redenetimoveis.com/javacv.jar,http://san.redenetimoveis.com/javase.jar,
http://san.redenetimoveis.com/jna.jar,http://san.redenetimoveis.com/customizer.jar,
http://san.redenetimoveis.com/jmf.jar,http://san.redenetimoveis.com/mediaplayer.jar,
http://san.redenetimoveis.com/multiplayer.jar,http://san.redenetimoveis.com/sound.jar"
height="550"width="550">
</applet>

java

editedSep27'12at11:55 askedSep27'12at11:30
Lucas_Santos
2,120 8 43 87

possibleduplicateofHowisimportdoneinJava? Curious Sep27'12at11:33

2 Ireadthisthreadbutthethreaddon'tanswermyquestion Lucas_Santos Sep27'12at11:35

5Answers

Indynamiclanguages,whentheinterpreter import s,itsimplyreadsafileandevaluatesit.

http://stackoverflow.com/questions/12620369/howjavaimportworks 1/3
5/19/2017 HowjavaimportworksStackOverflow
InC,externallibrariesarelocatedbythelinkeratcompiletimetobuildthefinalobjectifthelibrary
isstaticallycompiled,whilefordynamiclibraries asmallerversionofthelinkeriscalledatruntime
whichremapsaddressesandsomakescodeinthelibraryavailabletotheexecutable.

InJava, import issimplyusedbythecompilertoletyounameyourclassesbytheirunqualified


name,let'ssay String insteadof java.lang.String .Youdon'treallyneedtoimport java.lang.*
becausethecompilerdoesitbydefault.Howeverthismechanismisjusttosaveyousome
typing.TypesinJavaarefullyqualifiedclassnames,soa String isreallya java.lang.String
objectwhenthecodeisrun.Packagesareintendedtopreventnameclashesandallowtwo
classestohavethesamesimplename,insteadofrelyingontheoldCconventionofprefixing
typeslikethis. java_lang_String .Thisiscallednamespacing.

BTW,inJavathere'sthestaticimportconstruct,whichallowstofurthersavetypingifyouuse
lotsofconstantsfromacertainclass.Inacompilationunit(a.javafile)whichdeclares

importstaticjava.lang.Math.*;

youcanusetheconstant PI inyourcode,insteadofreferencingitthrough Math.PI ,andthe


method cos() insteadof Math.cos() .Soforexampleyoucanwrite

doubler=cos(PI*theta);

Onceyouunderstandthatclassesarealwaysreferencedbytheirfullyqualifiednameinthefinal
bytecode,youmustunderstandhowtheclasscodeisactuallyloaded.Thishappensthefirsttime
anobjectofthatclassiscreated,orthefirsttimeastaticmemberoftheclassisaccessed.At
thistime,the ClassLoader triestolocatetheclassandinstantiateit.Ifitcan'tfindtheclass,a
ClassNotFoundException isthrown.Tolocatetheclass,the ClassLoader usuallychecksthepaths
listedinthe $CLASSPATH environmentvariable.

Tosolveyourproblem,itseems youneedan applet elementlikethis

<applet
codebase="http://san.redenetimoveis.com"
archive="test.jar,core.jar"
code="com.colorfulwolf.webcamapplet.WebcamApplet"
width="550"height="550">

BTW,youdon'tneedtoimportthearchivesinthestandardJRE.

editedSep27'12at12:32 answeredSep27'12at11:53
Raffaele
16k 5 27 64

Andwhenaexternalpackageiscalledinmyimport,likegoogle(lookatmyimports).Whatwillbedone?I
needafreeinternetaccess? Lucas_Santos Sep27'12at11:58

Itseemsyourarchivesmustbeputinthesamelocationpointedtoby codebase ,andreferencedby


simplenames myjar.jar and foobar.jar .Seethisdoc RaffaeleSep27'12at12:05

Itryiedputthe <applet> taglikeyousaid,butdoesn'twork.Youcansawmycodeat


stackoverflow.com/questions/12604767/ Lucas_Santos Sep27'12at12:25

2 Whereis$CLASSPATHdefined?CanIchangeit?DoeseachJavaapplicationhaveitsown
$CLASSPATH?NikoBellic Jul26'14at22:59

Java'simportstatementispuresyntacticalsugar.importisonlyevaluatedatcompiletimeto
indicatetothecompilerwheretofindthenames inthecode.

Youmaylivewithoutanyimportstatementwhenyoualwaysspecifythefullqualifiednameof
classes.Likethislineneedsnoimportstatementatall:

javax.swing.JButtonbut=newjavax.swing.JButton();

Theimportstatementwillmakeyourcodemorereadablelikethis:

importjavax.swing.*

JButtonbut=newJButton();

answeredSep27'12at12:08
PeterMmm
16.1k 8 44 91

2 Goodforusingtheterm"syntacticalsugar"GabNov21'16at9:39

http://stackoverflow.com/questions/12620369/howjavaimportworks 2/3
5/19/2017 HowjavaimportworksStackOverflow

Importinjavadoesnotworkatall,asitisevaluatedatcompiletimeonly.(treatitasshortcutsso
youdonothavetowriteFullyQualifiedClassnames)Attheruntimethereisnoimportatall,just
FQCNs.

Attheruntimeitisnecessarythatallclassesyouhavereferencedcanbefoundbyclassloaders.
(classloaderinfrastructureissometimesdarkmagicandhighlydependentonenvironment)In
caseofappletyouwillhavetorigupyourhtmltagproperlzandalsoprovidenecessaryjar
archivesonyourserver

PS:matchingattheruntimeisdoneviaqualifiedclassnamesclassfoundunderthisnameis
notnecessarilythesameorcompatiblewithclassyouhavecompiledagainst.

answeredSep27'12at11:43
KonstantinPribluda
10.5k 1 18 29

Whathappens,isthatmyappletstopinalinewhereIcallamethodthatexistina importstatic
com.googlecode.javacv.jna.highgui.cvCreateCameraCapture; .But localhost worksfine,Igotthis
problemjustwhenIhotthe jar fileinmyserver.So,ifthe applet stopsinlinewherecallamethodthat
existsinthisimportedpackage,maybeainternetaccessrulecanresolve? Lucas_Santos Sep27'12
at11:50

1 Postyourobjecttaganddirectorystructure.Usuallyappletshaveaccesstoservertheycomefrom
KonstantinPribludaSep27'12at11:53

Questionupdated,the jar arein san.redenetimoveis.com/teste.jar Lucas_Santos Sep27'12at11:56

javac (or java duringruntime)looksforthe classes beingimportedinthe classpath .Ifthey


arenotthereinthe classpath then classnotfound exceptionsarethrown.

classpath isjustlikethe path variableinashell,whichisusedbytheshelltofindacommand


orexecutable.

Entiredirectoriesorindividualjarfilescanbeputinthe classpath .Also,yesa classpath can


perhapsincludeapathwhichisnotlocalbutissomewhereontheinternet.Pleasereadmore
aboutclasspathtoresolveyourdoubts.

answeredSep27'12at11:40
Curious
990 5 21

Theclasseswhichyouareimportinghavetobeontheclasspath.Soeithertheusersofyour
Applethavetohavethelibrariesintherightplaceoryousimplyprovidethoselibrariesby
includingtheminyourjarfile.Forexamplelikethis:Java:Easiestwaytomergeareleaseinto
onejarfile

answeredSep27'12at11:40
Kai
23.5k 8 61 89

Ihostmy jar fileinmyserver,soIneedtoedittheclasspathofmyservertoallusersaccesstheapplet


withoutproblem? Lucas_Santos Sep27'12at12:00

No,theappletwillactuallyrunontheclientside.Theclient'sclasspathistheimportantone. Kai Sep27


'12at12:03

SoIthinktheproblemisnotinmyclasspath,becauseinlocalhosttheappletrunsnormally.ButwhenIput
thejarfileinmyserver,theappletrunsuntilfoundamethodthatareinaimportedclassliketheimport
google.Don'tgenerateerror. Lucas_Santos Sep27'12at12:05

Trytospecifythelocationofthemissing.jarfileinthearchivetagofyourapplet(thehtmlcodeyou
updated).KaiSep27'12at12:10

http://stackoverflow.com/questions/12620369/howjavaimportworks 3/3

You might also like