Java Tutorial - Reflection Basics

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey what's up guys back again with another video in the java series this time i'm going to teach you about the basics of reflection so reflection is a topic that has been requested many times on my channel and i never got around to it but i thought today i would show you the basics of reflection and how you can use it within your programs so what is reflection that's the essential question here so in simple words it allows you to grab information on a class whenever you're running the program from within the program using code and this cannot be done with other programming languages so it's a unique feature to java i mean there is other programming languages that can do it i'm sure but before java this was a very unique feature um this cannot be done in major programming languages like languages like c plus and c and all that so yeah i'm going to show you the basics to get started here i'm not going to show you everything in this episode but i will get to showing you some more advanced stuff with reflection i just want to show you some basics on how you can start understanding it and using it within your code okay so first things first the essential building block of reflection within a java program is the class reference so this would be a class reference here so it's a reference variable that is called a class that's the type so this is what you use reflection upon so let's say that we want to get the class reference for a integer so you can do we need to give it a name just like any old reference variable is equal to and then integer dot class that's one way to do it so that's a that's basically a class reference for a primitive integer and we can grab information from that class reference now that we have it so we can do c1 dot and we have all this information here available to us to grab so let's just try printing out something very simple like get name so let's make a new output statement s out oops s out get name there we go so that should print out the name of whatever this reference um represents so let's run this and see what happens so there we go we get integer into the console because this is indeed an integer so that's how you get a class reference for a primitive type so let's say that you want to do it for a double you can do class c 2 is equal to double dot class you can do class c 3 is equal to long.class class c4 is equal to know that class you can even do null right or maybe not oh void it was void you can do void at class so that's how you get the class reference for any primitive that you might come across and so um this is not too useful at least at the moment for primitives but how can you get the class reference for some other types so let's say that you have a object so let's go ahead and create an object within our project here that we can work with for testing this new stuff so we're going to make a dog class so what is our dog gonna have let's have some just very basic stuff so prim uh private string name private integer age um let's do public so we're gonna need a constructor so public dog and this will be a no argument constructor so by default the name of the dog will be bob because you know any good old dog's name should be bob by default and the age will be two years old so public uh dog and this will be a constructor that has arguments so string name integer age so this dot name is equal to name this dot age is equal to h so this is a very basic simple stuff um so then we'll do public uh we'll just make some git or some getters and setters for our members here the name and the age members or fields whatever you want to call them so getter and setter boom and now we generate the four methods for these things here there we go and what's the problem okay we can ignore that that's fine so anyway um so how can we get a class reference for the dog class so we can do class c i guess we'll call it we'll call it dog class that's a better name so the class dog class is equal to dog.class just like we would do with the primitive so that's how you get the class reference for a dog type because our class here technically is a custom data type that we have just invented technically right um anyway so now that we have that like before we can we can grab information from it now so dog class dot get name and it should print out dog let's see what we get there we go so we get me.codysimpson.dog which is just the package name in front of it and then the class name itself pretty cool so let's see what other information we can grab from this so s out dog class dot so there's a lot of information we can grab from this we can get the constructors of this class we can get the fields of the of this class um we can get the methods of this class so as you can see here reflection allows you to get the detailed information of a class from within the code itself so basically the code is getting information on itself which is kind of a cool concept if you think about it so think about the possibilities here what is really possible with this so let's say that you have a library that you're using within your application or you're interacting with and you don't really know information about it until you're running the program let's just say that right so what you can do here is use reflection to get information on that library that you're using at runtime so you can start using it you can even call the methods of the library if you want to using reflection instead of you know like you would normally do with any normal class normal old class so you may ask why is this really useful because we can just you know declare objects um like we would normally do within a within code why would that be useful if we can just do it with you know normal objects so what makes this truly powerful is that you can access private members private uh fields of the classes that you're interacting with you can access all the intricate details of a class from a library or just anything right so you don't have to worry about being restricted you can actually look at it at runtime and then use it if you want to so it allows you to do some pretty cool stuff so one example is uh making a json to java like translator converting json text into java classes basically and the other way around too that's a one way that's one example of java reflection and there's some others like for my spigot series i think i said this already um you can use reflection to have multi-version support i'll leave some interesting resources in the description below so you can see some more information on this if you're truly curious if you want to but yeah besides that just to recap basically you can use reflection to access the intricate details of a class and its objects and all that stuff and even interfaces um you know anything right so it's really really powerful so again this is how you access the class reference for a undeclared dog class so you haven't made an object of dog yet you're just accessing it by calling the doc class thingy here that's one way to do it and so another way is let's say you do have a dog instance or an object as you might call it you can do dog dog is equal to new dog bob and he's uh four years old there we go so now we have a new dog object and so now we can get a class reference of that we'll call it dog class again is equal to and set and so instead of doing um we could again do dog.class but since we have an object here we can use it so dog dot git class and that's one way to do it you can call the git class method and that returns a class reference to the class that you um to the object that you have here okay so hopefully that makes sense it's literally the same thing except that you're calling it or you're accessing it a different way so now that we have that we can access information on it like we were doing a second ago so we can again print out the class name classname dot get name and there's also some other basic methods we can use to grab some basic information on a class reference here so interface so we can do dot class dot is interface and that returns obviously if it's an interface or not so you can get a class reference for a interface if we have one so yep so uh s out so hopefully you know this already arrays technically like a class behind the scenes so we can do is array and that will tell you if it's an array or not an array type so let's try diving deeper into this class that we have access to let's try accessing the constructors of this class so we can do constructors and that will obviously return the constructors of the class so it says returns an array containing constructor objects reflecting all the public constructors of the class represented by this class object in array of length the 0 is returned if this class has no public constructors or if the class is an array is an array class or if the class is or if the class reflects a primitive type or void so that's some good information that we could use so we know here that this class does have some constructors so we don't have to worry about checking to see if it returns 0 or not so we can now go back here if we do control q it says it returns an array of constructors here so we can make an array of of constructors to store that in so array of construct constructor array we'll call it constructors is equal to dog class dot gate constructors so now we have a new constructors array make sure you import constructor from the reflection package by the way um that's in java.lang.reflex that's where you find all the reflection stuff there okay if you want to check out the documentation uh so yeah now we have a an array of constructors here so we can just like we're doing with the class reference here we can use the constructor references to grab information on the constructors of the class so let's loop through this so for constructor constructor constructors and um for each of these we want to we can do constructor dot and then we can get a bunch of information like the parameter count the amount of parameters that are in the uh in the constructor the name of the constructor um the the declaring class which is just you know this one right here parameter types um exception types modifiers a bunch of information so let's try printing out some of this information so we can see what we got here so we'll do s out s out constructor name and so we'll do constructor dot get name there we go and oh yeah let's run this so we can see what we have up here and also what we have here now so let's run this and see what we get there we go so it says classname me.codysimpson.dog interface false array false um constructor name me.codysimpson.dog constructorname.isme.codysimpson.dog just because we have two constructors here which are both dog right there we go pretty simple but that's not very useful information let's try seeing if we can grab some more information from this before we do that though let's make a simple thing here new line and then we'll say constructors there we go just to divide it a little bit for orderedness orderliness and so let's see um let's see here let's try printing out the parameters of the constructor we can do that so we'll say s out params and then we'll do that so how do we get the params we can do constructor.getparameters and that obviously returns the params there we go so um actually if you look closely here you can do you can do a git parameter count also so you can determine um how many parameters are in are in the constructor that we're working with here so first let's do constructor dot get parameter count and if it's equal to 0 then we know it's a no argument constructor so there's nothing to print out right so we'll say no oops spit what the heck no no arg i can't type no r constructor i keep saying constructor it's just i like saying it like that because the ending here but it's constructor whatever um so if it's not zero arguments then we obviously have some stuff to print out so we can have a parameter array parameters is equal to constructor.getparameters and this obviously returns all the parameters so returns an array of parameter objects that represents all the parameters to the underlying executable represented by this object returns an array of length 0 if this if the executable has no parameters the parameters of the underlying executable do not necessarily have unique names or names that are legal identifiers of the java programming language all right cool all right so now that we have um well first before i continue here let me show you um obviously there's a pattern here there's a object reference for every single element of a class which you know makes perfect sense because we're deconstructing a class at runtime and then uh storing these uh elements in references and then we can grab information from them so yeah hopefully this all just makes sense so far um this is just a pattern and we're deconstructing a class so yeah anyway so uh parameter array parameters so now we can do another loop here so parameter parameter parameters so for each of these parameters let's do s out parameter let's see what information we can get parameter dot we can do get name like always so that's the parameter name and then a space and then plus parameter dot um let's see what else we can get oh we can get the type that's information that we should have so the parameter name and the type that's exactly that's pretty much all we need i think for a parameter um yeah that makes perfect sense so what this will do just to recap it's going to get a class reference of a dog and then it's going to get an array of all the constructors of that class and then it's going to loop through those constructors and it's going to get the parameters of that constructor if there are parameters and it's going to print out each parameter along with this type okay so let's see what happens let's run this there we go so it says class name dog interface false array false constructors constructor name meet.codysimpson.dog parameters no r constructor just because as you can see here we have a no r constructor and then second we have constructor name dog parameters arg0 is class java.lang.string which is the type and then arg1 integer is and that you can see right here so string name integer age there we go pretty cool so yep there we go so now we're breaking down a class step by step and getting the information from it which is really cool so let's see what else we can grab um let's think about let's see what let's grab the methods of this class so all the methods that we have here let's see how we can do that so down here let's do dog class dot and we can do get methods all right so we have two major um uh methods we can use to grab the methods here we can do get methods or we can do dig get oh i said dick get declared methods so get methods here returns every single public method of this class that we're working with here um even the methods that were inherited by any super classes that we're extending from or anything like that but this good declares methods method that we have here returns an array containing method objects reflecting all the declared methods of the class including the private method so it shows everything including the hidden methods of the class so but it only shows the methods that you're declaring in the class itself not anything inherited so it's only going to show these four methods here not anything inherited by the object class because of course every object um implicitly inhere inherits from the object class if you don't remember but uh yeah let me show you an example so you can see solidified what this actually looks like so let's try the get methods method first so that returns a method array so method methods is equal to dogclass.getmethods there we go import method okay so now let's loop through it so for ia integer i is equal to zero i is less than methods dot length i plus plus all right so now let's print out um the method so we'll say something like method number method number um and then like i so like method number and we'll do i plus one oops i plus one so let's say that'll say method number one starting from the first one and then we can actually print out the method itself so i number one a method number one um plus method methods i so grab the method from the array dot and then we can get the information from the method object that we have here so get name or yeah let's do again name before we do the return type so let's see what this looks like before we continue and boom so here we go so now we get all of the methods so one two three four five six 7 8 9 10 11 12 13 so these are all of the methods of the class including all of the inherited ones but let me rephrase not all the methods of the class again these are only the public methods of the class so if we did have any private methods it would not show up here so let me show you that so public or private void kill or yeah just kill yeah there we go so now let's run this and see if that shows up there yeah so as you can see kill does not show up it only shows the public methods of the class including the methods that were inherited so just public okay so hopefully that makes sense so let's print out some other information before we show how to do the other one so methods i and we can do git return type and this returns what is a return it returns a class reference so methods i return type dot get name get name sab return that shows the return type of the method and then let's put the method name so methods i get name and then what else so we want to do the parameters of the method right because that's another important element of a method if it has parameters so we'll do methods oops methods i dot get parameters as you can see here so get parameters and that returns our parameter array like we saw before so let's just um call arrays dot tostring and that will print out the array easily for us so let's see what this looks like let's try it out there we go so now we get all of the methods down here method number one java.lang.string getname and it has no parameter list as you can see right here so no parameter list good and so method number two void set name and then it has the parameter java.lang string argument zero and so on so it prints all the important information but one thing we are missing though is the access modifiers of it so like in this case public so let's see if we can print that on that information um let's put that right here in the front so we'll do methods i get modifiers there we go so modifiers will it should give us the modifier so it says returns the java language modifiers for the executable represented by this object so let's see what that returns okay let's run this now okay what the heck is that so of course it's not very useful to us at the moment as a number so we can print it out um as a string as we would normally see it just by doing modifiers modifiers dot or what is it modifier yeah dude dot two string there we go so we can pass in that number that was provided from get modifiers to modifier.2string and that should print out the modifier that we need so let's see there we go so now we get the modifiers so public public void uh public integer public final uh public bullion public public native integer public final native public final native public final name so these are the inherited methods at the end of course there we go so that's how you get the modifiers of a class that you're reflecting or using reflection upon pretty cool but let me show you how to do the um the get declared methods uh thingy method so get declared methods and obviously that returns the declared methods which represent all of the methods that you declared within the class alone and that includes also like i said before all of the private and hidden methods that you would normally not see with the other one so method array declared methods equals dogclass.getdeclare methods and we just need to make sure that we change this so let me copy this and change this to declared methods there we go so now i should print out all the information that we need let's try it out all right um let's put a space in between so we know where it starts and where it begins or whatever i just said the same thing twice didn't i okay let's try it out now there we go so now we got a space and method number one public java.lang.string getname uh public void set name public void set age public integer getage and then private void kill there we go so we got a private method now and as you can see all of the inherited methods are no longer listed as well so this is just an easy way to get all of the methods of the class even the private ones so if you think about it think about um this right so normally whenever you have a class that has private uh members um you cannot access them program prom programmatically you cannot access them using the program without using reflection so let me give you an example here so if we go right here this dog class does have a private kill method right this means that we cannot call kill it's not possible so if you if you can imagine that you've imported a library or or even if you're using your own code and you want to use private methods or you access private fields even you can use reflection to do so so think about the possibilities in that case right you can use any of the private stuff using the get declared methods method if you have a class reference of a class so hopefully that makes sense um yeah so just another example of how powerful this might be for your programs okay so the final thing i want to show you is how to get fields and by fields that just mean the uh the these things here the fields so prince um the fields and so how do we get the fields i'm sure you can guess by now right um there's a pattern so dog class dot get and you can get the fields there we go so get fields and returns a fields array so fields are field array field array fields is equal to dot class dot get fields there we go all right great and uh let's try looping through this so we'll do four field field fields and so let's just print out some basic information on each of these fields like their access modifier their return type and then their name so do modifiers dot tostring modifier.2string field.getmodifiers plus and then the name or no we want the return type now so field dot get return type or actually not return type i mean type you know what i mean right so field i get type dot get name and then final space is the name of the actual field itself so field login name and let's see what this looks like oops get name let's there we go so let's try this out now and there we go nothing printed out why is that well because the git fields method that we're using here only returns the public fields of this class that we're reflecting it only returns the public ones and these are both private so it's not going to return anything so let's make a public field here just to show you so test and let's try printing this out again or running this again and there we go so now we get public java.lang.stringtest but it doesn't print out the other ones because they're private like i said so how do we get all of the all of the fields even if they're private so let's try this out so get declared fields just like we do with the methods so with methods we do get declared methods to get all of the private and eternal methods of a class so this is how you get all the private and internal fields of a class so get declared field so let's try this out now and it should print out everything there we go so now we get name into i mean name age and then test there we go so we get all three of the class and yeah that's pretty much it that's all i'm going to show you for this episode this is a basic introduction to java reflection so now you should be able to access the internal information of classes interfaces and arrays i didn't show you interfaces in arrays but it's the same concept i'm sure you can figure it out this is how you access those things internally within your code dynamically and by dynamically i mean at runtime so you can grab information from something that you're working with at runtime without knowing what it is beforehand right so if i was to change this dog class here if i was to remove this and i was to rerun the code obviously it would still work so that's what i mean by dynamic pretty much no matter even if i change the code of the class it's still going to work because it's grabbing the information on the fly as we're running the program during runtime so hopefully that makes sense um but yeah if you have any questions about this reflection concept then please let me know i'm going to have some other episodes on reflection in the future i like how to invoke constructors how to invoke methods um using reflection and then some other important stuff so please stay tuned for that and let me know if you do want to see that other stuff so yeah and besides that i'll leave the code for this episode in the description below so make sure you check it out and you can bookmark it for future use for the future and like i said before i'll leave some resources in the description below so you can check it out if you're interested in some more information that i can use that you can use to understand this concept more deeply and also i'll leave a link to our discord community so you can get involved there you know hang out with us ask for help with if you have any questions or if you're stuck on something you can ask for help and somebody can help you or just get some new friends and finally you can also hit the join button below this video if you want to support me um you can join this channel as a member for as low as 99 cents a month five dollars or ten dollars so yeah if you want to support me then click that join button you can become a member and it comes with some cool perks like early access to all of my new videos a cool rank on my discord server and also you get to see yourself on the screen like you see right now so thanks to all of you who have supported me so far and thanks to all of you who are watching my video i appreciate you as well of course and that's it so if you like this video leave a like if you want to see more subscribe and peace
Info
Channel: Kody Simpson
Views: 6,556
Rating: undefined out of 5
Keywords: programming tutorial
Id: FIACGmzibAM
Channel Id: undefined
Length: 28min 1sec (1681 seconds)
Published: Fri Jan 15 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.