首页 > 编程知识 正文

javadeprecated,接口的default方法

时间:2023-05-04 06:59:13 阅读:109949 作者:4143

方案:

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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。