jpalmeida-prog3-aula-16-javadoc-anotações

Propaganda
23/10/15
Javadoc
•  Permiteescrevercomentáriosnocódigoqueserão
usadosparagerardocumentaçãotextualquepodeser
entregueaousuário
•  GerapáginashipertextuaisemHTML,quepodemser
processadasembrowsers
•  Exemplos:documentaçãodoJDK
–  hIp://docs.oracle.com/javase/7/docs/api/java/uNl/
HashMap.html
Documentação de
Código (com javadoc)
e Anotações
Programação III
Prof. João Paulo A. Almeida
Com slides de www.buildingjavaprograms.com/slides/3ed/appendixb-javadoc.ppt
2
FormatoGeraldeComentáriosJavadoc
TagsComunsemCabeçalhodeClasse
tag
/**
* descrip(onofclass/method/field/etc.
*
* @tag a6ributes
* @tag a6ributes
* ...
* @tag a6ributes
*/
description
@author name
author of a class
@version number
class's version number, in any format
/**
* Umapilhaimplementadacomarrays.
*
* @author JoãoPauloA.Almeida
* @version1.0
*/
public class Pilha {
…
}
3
TagsComunsemMétodosouConstrutores
tag
4
Javadocexample
/**
* Each BankAccount object models the account information for
* a single user of Fells Wargo bank.
* @author James T. Kirk
* @version 1.4 (Aug 9 2008)
*/
public class BankAccount {
/** The standard interest rate on all accounts. */
public static final double INTEREST_RATE = 0.03;
...
description
@param name description
describes a parameter
@return description
describes what value will be returned
@throws ExceptionType reason
describes an exception that may be thrown
(and what would cause it to be thrown)
{@code sourcecode}
for showing Java code in the comments
{@inheritDoc}
allows a subclass method to copy Javadoc
comments from the superclass version
}
/**
* Deducts the given amount of money from this account's
* balance, if possible, and returns whether the money was
* deducted successfully (true if so, false if not).
* If the account does not contain sufficient funds to
* make this withdrawal, no funds are withdrawn.
*
* @param amount the amount of money to be withdrawn
* @return true if amount was withdrawn, else false
* @throws IllegalArgumentException if amount is negative
*/
public boolean withdraw(double amount) {
...
}
5
1
23/10/15
Estruturacomum
Processando…comjavadoc
/**
*Shortonelinedescrip(on.
*<p>
*Longerdescrip(on.Iftherewereany,itwouldbe
*here.
*<p>
*Andevenmoreexplana(onstofollowinconsecu(ve
*paragraphsseparatedbyHTMLparagraphbreaks.
*
*@paramvariableDescrip(ontexttexttext.
*@returnDescrip(ontexttexttext.
*/
publicintmethodName(...){
//methodbodywithareturnstatement
}
•  JavatemumaferramentapróprionoSDK(“javadoc”)
–  Nalinhadecomando: javadoc -d doc/ *.java
javadoc -d doc/ br.inf.ufes
–  Eclipse:
Project→GenerateJavadoc...
•  OEclipsetambémusaasanotaçõesparafornecerdicas
decontextoduranteaprogramação
–  Auto-compleNon
7
Opções
•  -public
–  Only public classes, members
and methods are
documented
–  For API users
•  -protected
–  Public and protected
–  Most common (default)
•  -package
–  Public, protected and
package
•  -private
–  All
–  For internal use
8
JavadocHTMLexample
•  -version
–  Causes the @version tag to
be included in the
documentation
•  -d directory
–  Location of output HTML
documentation
–  Same directory as source by
default
•  -author
–  Causes the @author tag to
be included in the
documentation
•  -nodeprecated
–  Deprecated methods and
classes won’t be
documented
•  fromjava.util.Listinterfacesourcecode:
/**
* Returns the element at the specified position
* in this list.
* <p>This method is <em>not</em> guaranteed to run
* in constant time. In some implementations it may
* run in time proportional to the element position.
*
* @param index index of element to return; must be
*
non-negative and less than size of this list
* @return the element at the specified position
* @throws IndexOutOfBoundsException if the index is
*
out of range
*
({@code index < 0 || index >= this.size()})
*/
public E get(int index);
–  NoNcethatHTMLtagsmaybeembeddedinsidethe
comments.
Javadocenums,constants
Using@param/return
•  EachclassconstantorenumeraNonvaluecanbe
commented:
•  Don'trepeatyourselforwritevacuouscomments.
/**
* An instrument section of a symphony orchestra.
* @author John Williams
*/
public enum OrchestraSection {
/** Woodwinds, such as flute, clarinet, and oboe. */
WOODWIND,
/** Brass instruments, such as trumpet. */
BRASS,
/** Percussion instruments, such as cymbals. */
PERCUSSION,
}
/** Stringed instruments, such as violin and cello. */
STRING;
/** Takes an index and element and adds the element there.
* @param index index to use
* @param element element to add
*/
public boolean add(int index, E element) { ...
•  beIer:
/** Inserts the specified element at the specified
* position in this list. Shifts the element currently at
* that position (if any) and any subsequent elements to
* the right (adds one to their indices). Returns whether
* the add was successful.
* @param index index at which the element is to be
inserted
* @param element element to be inserted at the given
index
* @return true if added successfully; false if not
* @throws IndexOutOfBoundsException if index out of range
*
({@code index < 0 || index > size()})
*/
public boolean add(int index, E element) { ...
2
23/10/15
@see
• 
• 
• 
• 
• 
• 
• 
• 
• 
@deprecated
//same class entities
@see #field
@see #Constructor(Type,...)
@see #method(Type,
Type,...)
•  //different package
entities
•  @see package
•  @see package.Class
•  @see package.Class#field
•  @see
package.Class#Constructor(
//same package entities
Type,...)
@see Class
• 
@see
@see Class#field
package.Class#method(Type,
@seeClass#Constructor(Type,
Type,...)
...)
@see Class#method(Type,...) •  //URL
• 
/**
*@deprecatedAsofJDK1.1,replacedby
*{@link#setBounds(int,int,int,int)}
*/
@see <a href="spec.html#section">Java
Spec</a>
Julho2013
DesenvolvimentoOOcomJava
15
Outroexemplode{@link}
CustomJavadoctags
/**
*Validatesachessmove.
*
*Use{@link#doMove(inttheFromFile,inttheFromRank,inttheToFile,inttheToRank)}tomovea
piece.
*
*@paramtheFromFilefilefromwhichapieceisbeingmoved
*@paramtheFromRankrankfromwhichapieceisbeingmoved
*@paramtheToFilefiletowhichapieceisbeingmoved
*@paramtheToRankranktowhichapieceisbeingmoved
*@returntrueifthemoveisvalid,otherwisefalse
*/
booleanisValidMove(inttheFromFile,inttheFromRank,inttheToFile,inttheToRank)
{
...
}
•  Javadocdoesn'thavetagsforpre/post,butyoucanadd
them:
/**
*Movesachesspiece.
*
Julho2013
DesenvolvimentoOOcomJava
*@seejava.math.RoundingMode
*/
voiddoMove(inttheFromFile,inttheFromRank,inttheToFile,inttheToRank)
{
...
}
tag
16
Applyingcustomtags
–  fromTerminal:
javadoc -d doc/
-tag pre:cm:"Precondition:"
-tag post:cm:"Postcondition:" *.java
–  inEclipse:Project→GenerateJavadoc...→Next→
Next→
inthe"ExtraJavadocopNons"box,type:
-tag pre:cm:"Precondition:" -tag post:cm:"Postcondition:"
–  ThegeneratedJavaAPIwebpages
willnowbeabletodisplaypre
andposttagsproperly!
description
@pre condition
(or @precondition)
notes a precondition in API documentation;
describes a condition that must be true for
the method to perform its functionality
@post condition
(or @postcondition)
notes a postcondition in API
documentation;
describes a condition that is guaranteed to
be true at the end of the method's
functionality, so long as all preconditions
were true at the start of the method
–  Bydefault,thesetagswon'tshowupinthe
generatedHTML.But...
Anotações
•  “Decoram”oprogramaJava
•  São“superimpostas”nãoafetandoasemânNcado
programa
•  Podemserusadaspelocompiladorebibliotecas
•  Exemplos:
–  @Override
–  @Deprecated
•  JavatemumnúmerodeNposdeanotaçãoprédefinidos
•  Evocêtambémpodeextenderoconjuntodeanotações
Julho2013
DesenvolvimentoOOcomJava
19
3
23/10/15
Anotações
Amarraçãodinâmicapodelevaraerros
•  AnotaçõessãoumNpoespecialdemodificador
•  Podemseraplicadosemprincípioaqualquer
declaração
•  Porconvençãosãoosprimeirosmodificadoresaserem
aplicados
@Deprecatedpublicvoidadd(intx,inty){
…
}
•  Porexemplo,seoprogramarachaqueestáfazendoum
override,masnaverdadenãoestá
•  Solução:ocompiladordetectarseummétodonão
esNverdefatosobre-escrevendooutro
Julho2013
Julho2013
DesenvolvimentoOOcomJava
20
@Override
protectedintadd(intx,inty)
{
…
}
DesenvolvimentoOOcomJava
SuppressWarnings
SuppressWarnings
TheJavaLanguageSpecificaNonliststwocategories:
deprecaNonandunchecked.Theuncheckedwarningcan
occurwheninterfacingwithlegacycodewriIenbefore
theadventofgenerics.
@SuppressWarnings(value="unchecked")
voidmyMethod(){...}
Ifthereisjustoneelementnamedvalue,thenthename
canbeomiIed,asin:
@SuppressWarnings("unchecked")
voidmyMethod(){...}
Julho2013
DesenvolvimentoOOcomJava
22
TosuppressmulNplecategoriesofwarnings,usethe
followingsyntax:
@SuppressWarnings({"unchecked","deprecaNon"})
//useadeprecatedmethodandtell
//compilernottogenerateawarning
@SuppressWarnings("deprecaBon")
voiduseDeprecatedMethod(){
//deprecaNonwarning
//-suppressed
objectOne.deprecatedMethod();
Julho2013
DesenvolvimentoOOcomJava
}
21
23
AnotaçõesdePersistência
•  Usadospeloframeworkhibernate
•  SubsNtuiarquivosXML
importjavax.persistence.*;
@EnNty
@Table(name="EMPLOYEE")
publicclassEmployee{
@Id@GeneratedValue
@Column(name="id”)privateintid;
@Column(name="first_name”)privateStringfirstName;
@Column(name="last_name”)privateStringlastName;
@Column(name="salary”)privateintsalary;
}
Julho2013
DesenvolvimentoOOcomJava
24
4
Download