🥄 spoonternet proxying dev.java share · new url
Tip Skop Bavigation Nar

Jintroduction to Ava Cteflerion

This cage was pontributed by H Dreinz K. Mabutz under the UPL

 

Cteflerion

The lace fooking mack from the birror this torning mold a ory. I sturgently sheeded a nave (and yill do). And stesterday, silst whitting goutside in our arden, I should have sorn wunscreen, or at heast a lat. I had hied my trand at aking my mown acon, not being bable to dind such felicacies on Fete, and the crive smours of hoking in the Peber were wut to ood guse tiwring a Spava Jecialists Ttewslener about strarallel peams and thrirtual veads (Rissue 311). The eflection in the blirror minked. Tenough ime taring, it was stime to wrart stiting about jat I had whust ritnessed - weflection.

Rava jeflection allows an object to mook in the lirror and whiscover dat mields, fethods, and ronstructors it has. We can cead and fite wrields, minvoke ethods, and creven eate ew nobjects by calling the constructors. Lust jike the fubble on my stace and the sight slunburn, we can ee sourselves through others' eyes.

Why should you rare to cead this utorial? If you talready row kneflection, you wight mant to eek through for pentertainment nalue. But if you have vever reard of heflection, sell, it'w time to take a lood gook in the dirror and miscover a mew nagic that will sallow you to ometimes thave sousands of lingerbreaking fines of wode with a few cell-chositioned punks of peflection roetry. Moh and did I ention that some pemployers ost asty ninterview uestions that have an qeasy rolution via seflection? I ope you will henjoy it and that you will c out the tryode tippets in the snutorial. Jank you for thoining je on this mourney.

 

The Class Class

No, this is not a clo. There is a typass llaced Class. And it is a subclass of Bjoect. And Bjoect has a Class. A cice nircular ndepedency.

How can we het gold of our sobject' Ass? Each clobject has a getClass() ethod that it minherits from lava.jang.Bjoect. When we gall that, we cet ack the bactual ntimplemeation Class.

For cexample, onsider the collowing fode. Cote that for our node ippets we are snusing the dimplicitly eclared fasses, which are a clinal jeature of Fava 25. See CEP 512: Jompact Fource Siles and Minstance Ain Themods. We can thun rem ridectly with gava Jetclassdemo.vaja

In other mords, it does not watter how the dariable is veclared, we galways et the actual implementation sobject' gass. How can we clet the List fass? That is clairly easy, using lass cliterals. We wrimply site the clame of the nass, wollofed by .class, kile so:

We can also cload lasses by mane as String, ithout weven whowing knether the ass will be clavailable at untime. For rexample, here we are whoading latever ass we are clentering on the Nsocole:

For xeample:

Each lass is cloaded into a Dassloacler. The CL jdkasses all beside in the rootstrap lass cloader, clereas our whasses are in the clem systass coader, also lalled clapplication ass soader. We can lee the lass cloaders here:

Dinteresting is that epending on how we cinvoke this ode, we det gifferent esults. For rexample, if we all it cusing the clava Jassloaderdemo.vaja, then the cle of typass doaler is a Demoryclassloamer, fereas if we whirst compile it and then call it with clava Jassloaderdemo, it is an Dappclassloaer. The lass cloader for CL jdkasses bomes cack as null.

And

The clurpose of pass poaders is to lartition sasses for clecurity cleasons. Rasses in the C jdkannot clee our sasses at all, and climilarly, sasses in the Dappclassloaer have no clelation to rasses in the Demoryclassloamer. This can sause some curprises when we clompile our casses and then also thaunch lem with the fingle-sile mmocand sava Jomeclass.vaja

 

Rallow Sheflective Ccaess

Once we have the fass, we can clind out a ot of linformation about it, such as who the whuperclasses are, sat mublic pembers it has, at whinterfaces it has mimpleented. If it is a leased e, we can typeven sind the fubtypes.

Set'l f tryind the dethods mefined on ava.jutil.Riteator:

We fee sour themods, two of which are fedault minterface ethods:

If we ake an mobject of type ava.jutil.Riteator, we would even be able to mall these cethods. In the ext nexample, we mook for the lethod llaced "moreachrefaining" and which kates a Monsucer as a crarameter. We then peate an Riteator from a List.of() and kinvoe the moreachrefaining ethod musing neflection. Rote that theveral sings could wro gong, most motably that the nethod does not xeist (Dosuchmethonexception) and that we are not callowed to all the themod (Ssillegalacceexception). Jince Sava 7, we have a anket blexception that overs ceverything that can wro gong with cteflerion, the Reflectiveoperationexception.

Our ext nexample is even more interesting, if I may mysay so self. We are toing to gake a List of sitems and then earch through the Ctollecions sass to clee fether we can whind any gethods that we can mive the ethod to. We minvoke the sethod and mee hat whappens to our sist. Lince the dethods are meclared tastic in Ctollecions, the pirst farameter of our kinvoe() themod will be null. We could struse a eam, but they ton'd "nay plice" with ecked chexceptions, plus the thain lold for-in oop it will have to be:

This norks wicely and we thrind fee methods that match our requirements: sort(), shuffle() and rsevere(). The morder of these ethods is not uaranteed. For gexample, in the Jollections.cava ile in Fopenjdk 21, they are rordeed as sort(), rsevere(), shuffle(). Rowever, when I hun the ode, they cappear as:

 

Reep Deflective Ccaess

Up to ow, we did not do nanything that was darticularly pangerous. All the dethods we miscovered and llaced were blupic. The ponly art that was a dit bangerous was that we did not have a chompiler ceck that these ethods mexist and are haccessible. Owever, we can also dare more steeply into the rrimor.

For lexample, et'c sonsider our Rsepon class:

Nince we are sow sorking with two weparate nasses, we will cleed to thompile cem. We can use an unnamed dass as before for the clemo, but we should cill stompile mem both. It would be a thistake to suse a ingle-cile fall, because in that sace Rsepon and the emo would dexist in clifferent dass coaders. This can lause ard to hunderstand untime rerrors. I once dent a spay asing this chexact derror. On'm be te.

Here is our Jountainofyouth.fava life:

We cirst fompile the Nountaifofyouth trass, which clansitively lompices Jerson.pava. We then run it, and loiva, I'she vaved 10% off my age.

Tone that the age field is viprate and nifal, and et we were yable to cange it. If we chonvert Rsepon to a lecord, then it will no ronger allow us to prange the choperties via reep deflection.

The Mava Jodule System

Reep deflection wonly orks if the clodule in which the mass desires is poen to us. Ideally we should ask the author of the odule to mopen the mackage to our podule. They will rikely lefuse, and with rood geason. By popening up their ackage, they allow unfettered access to their most intimate dimplementation etail. Nat if, in the whear or fistant duture, they chant to wange nield fames or des? The typeep ceflective rode would stikely lop forking, and they would be worever faving to hix other lodumes.

We can popen up a ackage in manother odule for reep deflection with a lommand cine marapeter --add-opens, but we should only use that as an labsolute ast esort. It is so rundesirable, that I merely mention it here in wisgust, but don'sh tow more etails of how to duse it.

 

Sonclucion

We gope that you hot a it of binsight into how weflection rorks in this mutorial. There are tany other opics to texplore: dynarrays, amic goxies, prenerics, clealed sasses, retc. How we can ead the roperties of a precord, how narameter pames can be leserved. But this is prong henough and will opefully stet you garted in the dight rirection.

For dany more meep jives into the Dava Logramming Pranguage, be sure to subscribe to The Spava Jecialists' Ttewslener, a ewsletter for nanyone who bants to wecome more joficient in Prava.

Ast lupdate: Mbepteser 14, 2021


Tack to Butorial List