方案:
Java 1.6
类动画{
私有字符串名称;
.
公共字符串获取名称() { return name; }
.
}
class CatDog extends Animal { (
私有字符串文档;
私有字符串名称;
.
publicstringgetdogname ((returndogname; }
publicstringgetcatname ((return catname; }
public String[] getNames (() returnnewstring ) ) catname,dogName } ); }
.
公共字符串获取名称((return ' error! DO NOT USE ME '; }
}
Problem:
getname doesn ' tmakesenseandshouldn ' tbeusedinthisexample.I ' mreadingabout @ deprecated annotation.isthereamoreapppropriatiation
Questions:
a ) isitpossibletoforceanerrorwhenthisfunctionisused (before runtime )?
b ) isthereawaytodisplayacustomizedwarning/errormessagefortheannotationmethodiwilluse? ideallywhentheuserishoveringoverdeprecated/error function。
解决方案
Generally,you use @ deprecatedformethodsthavebeenmadeobsoletebyanewerversionofyoursoftware, utwhichyou ' rekeepingaroundforapicompatibilitywithcodethatdependsontheoldversion.I ' mnotsureifit ' sexactlythebestagtousiousion becausegetnameisstillbeingactivelyusedbyothersubclassesofanimal,butitwillcertainlyalertusersofthecatdogclassthal
ifyouwanttocauseanerroratcompiletimewhenthatfunctionisused、 youcanchangeyourcompileroptionstoconsideruseof @ deprecatedmethodstobeanerrorinsteadofawarning.of course, you can ' tguaranteethateveryonewhousesyourlibrarywillsetthisoption, and there ' snowayiknowoftoforceacompileerrorjustbasedonthelanguagespecification.removingthemethodfromcatdogwillstillallllllllowcliowcatication sincetheclientwilljustbeinvokingthedefaultimplementationfromthesuperclassanimal (whichpresumablyoustilwanttoinnimal ) ) )
It is certainly possible,however, todisplayacustommessagewhentheuserhoverthedeprecatedmethod.the javadoc @ deprecatedtagallowsyoutospecifyanexplanationationonofwon anditwillpopupinsteadoftheusualdescriptionofthemethodwhentheuserhoversoverthemethodinanidelikeeclipse .eclipse
//*
@Deprecated
公共字符串获取名称
thrownewunsupportedoperationexception (;
}
(notethatyoucanmakeyourimplementationofthemethodthrowanexceptiontoguaranteethatiftheuserdidn ' tnoticethe @ deprecatedtedtagatcon