Java Reflection Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
well hello internet and welcome to part 10 of my design patterns video tutorial today we're going to talk about something that isn't a design pattern however it has been brought up many times and that is the Java reflection API in this tutorial I will unveil exactly what reflection is and make everything a hundred percent understandable so let's get into exactly what is the Java reflection API I think most of the confusion that revolves around this topic is based off of the name whenever people hear reflection they immediately think it's a technique to use inside of Java no it is and it's a library just like everything else and also the names kind of vague and sounds mysterious I think better-class manipulator would be a better name for reflection so every time you hear the word reflection think of class manipulator because that is exactly what it is the Java reflection API is used to manipulate classes and everything in a class including fields methods constructors private data private methods etc however you have to understand that because using the reflection API is most often dynamic it can slow down a program because the java virtual machine can't optimize the code if it is in fact dynamic the reflection api can't also be used with applets because the added security at applets require and also remember that because this api allows you to do things like access private fields and methods it should be used sparingly or else potentially destroy the complete logic of your program now on to what i think is the greatest and coolest thing about the Java reflection api have you ever dreamed that somebody could pass you say a string such as method to execute this is a method that you'd want to execute on your own dynamically and then you'd be able to dynamically take this string and execute it just as if it was a method that was pre-built directly inside of your code well with the Java reflection API you're going to be able to do that now on with a code I'm going to explain everything that goes into this guy now the very first thing I'm going to do here is I'm going to use some code that I originally created whenever I created my abstract factory design pattern and again reflection has nothing really to do with design patterns however it is often used with design patterns and inside of this guy I'm going to create some it's stuff that I'm then going to go in and access so this is just dummy code I'm gonna split 100 inside of here as a string I'm going to show you in a second how to grab private information however that's just a small part of what we're going to be doing here I'm going to create myself a private method that is just going to return a string how did you get this it's a pretty simple stuff I'm going to create another private method inside of this it's going to return a string get other private and it's going to receive an integer and I'm just going to call it this int it's also going to receive a string and I'm going to call it that string and in doing so I'm going to show you how to pass any type of value into things like this and then it's going to go return how did you get here and then pass back that information back onto the screen so just putting this stuff together so that I will be able to come in here and play around with all these private methods and pass information around using this API then I'm going to go public and I'm also going to create a constructor and I'm going to show you how to run a constructor using the reflection API as well and then it's just going to print a message out the screen telling you that the object has been created and then also that you pass certain information into this constructor so by the end we're pretty much going to do just about everything you can do with reflection random string and then in the next part of the tutorial I'll actually use it in a real-world scenario you can kind of use this as a cheat sheet from now on whenever you want to dabble with the reflection API and now we're going to go into testing reflection Java I'm just going to start typing some stuff in here so let's say that you wanted to get the class object for UFO enemy ship how would you do that well I'm just gonna call this reflect and all this code is available in a link underneath the video and it's extremely heavily commented like I said I wanted this to act kind of like as a cheat sheet for reflection and there you go and that is going to get you your class object for the UFO enemy ship pretty simple stuff and let's say you wanted to get the class name for this object also pretty simple I'm just going to go create myself a string and then call reflect class get name and that's exactly what it's going to do for me I could then print this name out on-screen he's you know just by going classname and then I'm gonna throw in a carriage return if we execute that you can see UFO enemy ship the name of the class pops our aid up there on our screen for us to use so kind of simple stuff we're going to get into much more complicated things don't worry about it you could also check modifiers for a class so let's say you wanted to see if a class was public or not we're going to create an integer here and I'm going to call it class modifier and I'm covering a whole bunch of things that you might not often use but just want to get into a whole bunch of things here so you're just going to go like that it's going to give you the class modifiers for this guy and then I'm going to a system.out.print and then I can just simply come in here and type in mod a fire and check if it's public is public and then inside of here I'm just gonna type in class modifier so pretty simple and then we get true comes back and other class modifiers that you could check for would be is abstract is final is interface is private is protected is static is strict is synchronized is volatile and there's a couple other ones but those are the main ones that you could be able to check for all right so let's move on here and if we bounce over to UFO enemy ship you can see right there see public and that's why that came back true now if you'd like to get a list of different interfaces used by a class well this class doesn't have those but in the situations in which you would have them they would all be saved inside of a class array and I'm just going to call this interfaces of course you don't want that equal sign in there select class get interfaces right like that and that would return a array full of class interfaces that are attached to the class but like I said I don't have any so there's no point in doing that you could also get the superclass for UFO enemy ship just by going class and I'm going to call this class super because that's what it is and then you're just going to type in reflect class again reflect class remember is the name for this guy right here that holds the reference to the UFO enemy ship class okay so you don't have to use that you can use any name you want and just type in class super class and that's going to return super class for that guy and then of course make that lowercase then if I would want to print that information out on a screen now that I got the superclass I just come in here and go class change that to class super followed by get name right like that file save it execute and you can see enemy ship pops up so that's how you get that so you're just manipulating the class that's all you're doing it's nothing tricky here you could also get the object methods and return types and parameter types and all a bunch of the different things how you do that as you go and create yourself a method array and I'm going to call this class methods and then just go reflect class get methods right like that it's gonna get you a whole array of different methods and then if we zoom in here on this guy it's going to pop up a message for us there you go import method and then we look down here until we see java.lang reflect see that's reflection so just click on that and then I'll get you the libraries that you need and then if you want to cycle through all these different libraries no problem just use the enhanced for-loop and just go method because that's the class name you're using I'm gonna go method and in class methods is the array name that I want to cycle through pretty simple and then if I want to get the system name say that I type inside of here method name then I want to get the method name I'm gonna type in method get name again see typing in same thing over and over again before I go and execute that guy let's say that you'd also like to know if this method is a getter or setter method that's pretty simple you're just gonna go method again get name and then bounce out here and go starts with and see if it starts with get to see if it's a getter method system.out.print in this situation I could go getter method else if I'm just going to copy this I could also of course come in here and say set that's going to tell me if it's a setter method then just change that to s there you go so pretty simple way of doing that as well now before we leave this enhanced for say we also wanted to get the return type for all the different methods oh pretty simple for third type then just go method get return types that's pretty cool there you go now you get your return types as well you could also get all the different parameter types for all of these methods but think about it what is that going to main as potentially a bunch of them so that means you need an array we're just going to go parameter type is going to be the name I'm going to give that and to get all those you go method get parameter types so I told this this kind of be like a cheat sheet sort of thing then let's say one come in here parameters print that on on the screen and then we want to go in there and list all of them out so I'm going to do another enhanced for inside of the other enhanced for except this is going to be changed to class because its parameters and not methods change that to parameter and then we're going to be cycling through this array so we're going to grab that from the array paste that there and then if we want to I'll put those onto the screen also pretty easy to do they sit there and go parameter get name for the parameter and there you go that's gonna output all the parameters for that method and then let's say after we get out of here we just want to do another new line so I'm just going to do that septum I type in written line and I'm also see on type in print line there cuz that makes sense got a little bit crazy and just type system.out.print so that's all I'm doing here so if I'll save that no I did was change all the basics prints into print lines and we can execute it and see a whole bunch of things come on the screen and there you go so what are we doing here well we printed out UFO enemy ship true like you saw before enemy ship is the super class name and then we started printing out the method name there's method name return type for that method name is void and then the parameters for the method called follow heroship there are none see there's nothing listed here then we go on to our next method turn to void parameters there are none let's get down here until there are parameters you can see right here here's the setter method returns nothing parameters it does have a parameter and that parameter is string and you can see all of that information that is being accessed directly from that class that's pretty cool now let's say you'd like to access class constructors and we're nowhere near being done here I'm actually getting into the simple stuff right now well we just go constructor create a constructor right there and it's giving me an error that means I need a library and I'm just going to call it constructor give it a initialized value of null zoom in on it's going to give me an error it's going to say import constructor job or reflect air got that all soda and I'm also going to show you how to create an object by accessing a constructor I'm just going to call it constructive to initialize it with a null and then we'll start playing around with this stuff so we're going to go constructor and remember reflect class is a reference to our class UFO enemy ship dot Java up there and if we want to get this constructor we're just gonna go get constructor say this stuff isn't hard to memorize it just takes a little bit of practice after you play with it for a little bit you'll get it okay so what does our constructor do inside of UFO enemy ship that's the stuff I just created let's grill down here and look at what else we got well here's our constructor and it receives an enemy ship factory called ship factory but that doesn't matter so what are we gonna have to do we're going to need to pass it a class called enemy ship factory or an object so bounce back over here and to pass it an object we're gonna go new class brackets right there and this is used to receiving multiple different parameters but in this situation it's only going to receive one so I'm going to go enemy ship factory dot class because that's what it is and there you go and it's going to give me an error so just drift over top of it there it is add throws declarations surround with try multi catch click on that you don't have to remember any of these exceptions which is always a good things no point in memorizing all that stuff now let's say you wanted to call a constructor by passing parameters to create an object how would that be done pretty simply actually and we're going to be working with this guy right here constructor two so I'm going to go constructor two and basically going to do the same thing it's going to be reflect class get constructor and if we want to pass it an integer we're going to go into class remember what we're doing here bouncing to this guy this is the guy that we're going to be playing with in this situation saying here's that constructor that I specially created to receive two parameters first an integer then a string that's going to define our integer we're going to pass and then this is going to define the string that we're going to pass and if we want to get an instance or an object for it we go new instance and if we want to pass values to it saying initial arguments I'm going to say 12 for my integer this is just totally random and inform my string I'm just gonna say random strength in their yarn and now it's going to kick back an object for me and it's also going to kick back an error message and what's it going to say it's going to say add catch Clause to surrounding try yes yes yes yes that's what I want to do so just click that and there you go your error message just went away and it just added an additional bunch of different catch clauses inside here if you'd like to return the parameters for a constructor well again what's that mean there's probably going to be more than one so anytime there's going to be more than one chances are you're going to want to create yourself an array class so I'm just going to call this construct parameters is equal to constructor get parameter types and if you expect there to be more than one its parameter type so you expect there only to be one its parameter or tight so this is what you want to use now if you want to cycle through all those what do you do it's all simple we're just going to go class parameter and then we're going to do construct parameters so construct parameters there you go and then cycle through them also gonna be simple what do you think we're going to type we're gonna type in parameter which is this guy right here okay after a while you can kind of almost guess what this stuff is that'll get you all your parameters now I'm gonna go and create myself UFO enemy ship new enemy ship and initialize it with null and what I'm gonna do here is create a UFO enemy ship object by calling new instance also gonna go enemy ship factoring because I'm going to need to pass enemy ship factory to it to initialize it but it doesn't matter what it actually does reflexions actually used very often whenever your tube debugging a program so that's what a lot of this stuff here is and then we can just go what we're gonna do I'm not going to throw it a try block even though I know it goes in it because I'm gonna let Eclipse handle that for me I'm gonna go new enemy ship and if I want to use my constructor to get me a new UFO enemy ship well it doesn't know what it is so I'm going to have to tell it to cast it to UFO enemy ship and then call my constructor on it new instance and that new instance is requiring that I pass over a ship factory now if you don't know what I'm doing bounce over here again scroll through and you can see right here here's the constructor and what's it being passed an enemy ship factory see so that's why I'm passing it even though the enemy ship factory really doesn't need to do anything that's how it works and what's it gonna do it's gonna give me some errors telling me that I need to surround it with a try and multi catch block so let it do that and now that I've created this guy I'm gonna be able to call methods inside a UFO enemy ship just like any other object so I'm gonna go new enemy ship and let's say I wanted to call set name which is something that UFO enemy ship has somewhere where is it ah it's actually an enemy ship yep there it is see set name so this is the method I want to call here on this guy so no problem I'll just do that and I'm just gonna throw something junkie in here I'm gonna type in X 2 1000 you know it's just nothing doesn't have any real meaning and then I'll say I want to print some stuff out I can come in here and go enemy ship name like that then go new enemy ship I know what I'm gonna type if I want a name for something get name because that's gonna be my default that pretty much is used everywhere right I can file save it and we can execute this and see all these different things start popping up and you can see you sent 12 and random string where did this come from so let's go back and look at what we were doing here see this guy right here whenever I created this object see there is the object constructor - and then here is where I called my personalised constructor see integer string + 12 + random string is what I passed and 12 + random string is what it spit back at me and if we jump over here you can see this guy right here UFO enemy ship receives an integer in a string and what does it do it spits out you sent number and random string so that actually created that object whenever it called this personalised constructor right here and then spit it back on screen so let's go back here see what else it did down here you can see enemy ship factory you can see with this guy right here this is where we got our enemy ship factoring see I wanted to get the parameter for the constructor so what is the constructor this is the basic constructor and it's saying that one of the parameters are the only parameter that it kicks back his enemy ship factor and then the final thing I did was I set the name to X t1000 and then I told this newly created object to call the method name and what did it do print an enemy ship and there it is so you can see that I'm manipulating that object directly inside of this guy so I don't even need them in the beginning of what's cool about reflection I can also access private fields using the reflection API and how you do that is since you want a field you're going to type in field and then I'm going to call this private string name and give it a initialized value of null and then it's giving me an error message right here and that just means import and I want to look for field Lang reflect just click on that and there that message goes away because I now have the needle library and you can see all the libraries way up here say there's the field library that I just added to it there's a whole bunch other libraries so now that I have this guy I want to create a UFO enemy ship object so I'm going to go UFO enemy ship this has nothing to do with reflection I'm gonna call it enemy ship private is equal to a new UFO enemy ship and then I'm gonna pass it ship factory which I created earlier so that it likes me there it goes then I'm going to define the private field that I want to access here and what's cool about this is I'll be able to access any field with just this name even if it's sent dynamically over so let's say private string name is the field that I want to be sent back to me I'm gonna go UFO enemy ship class and then get declare field and the field that I want to get is actually going to be represented with a string and it's ID code right like that so you can see synthesis is a string I would be able to dynamically be able to grab all this information out of here and it's giving me another error because I need to wrap this in a try-catch blocks around with try multi catch so I'm gonna give myself a little bit of room but just to prove to you that this could all be handled dynamically meaning remember I said back in the very beginning let's look at it would it be cool if somebody could pass over just a method name as a string and I could execute it dynamically well that's what I'm doing right now so let's get back to that so here I am and I could say string ID code sample string and then inside of that write in ID code like that and then type in ID code string which is a string like I said it can be passed over dynamically this is what's cool about it I paste that in there but of course make sure you get the variable name right or field name and this is the guy that I want to get this guy right here it's actually lower case in this situation so I want to make sure that I have that as lower case okay boom so we are got that safe so that's how you can dynamically access any field with just access to its name see it's all dynamic so it's really cool wrap your head around that some of you guys are going to get it some of you're not but think about it because it's really cool once you're able to figure out how to do that and then what you're going to need to do is come in here because we're going to be trying to access a private field well we need to shut down the security so that we're allowed to access private fields and how you do that is go private string name which is this guy right here saying it's the field and you want to shut it down just say set accessible and then that's going to be marked as true so that's going to allow you to go in there and get yourself some private field data now once you have that set up if you want to go in there and save that private field data as a string for example I'm just gonna go value of name doesn't matter what it is we're gonna cast it into being a string and then you just go private string name which is name of the field git and then I'm going to type in enemy ship private put that there and you can see here enemy ship private is the name for my UFO enemy ship object so enemy ship private you want to list inside of here whatever the name for your object is and of course it's giving me another error saying put some more dry catch blocks and I always do it this way I always let it do the work and find my proper catch blocks so you can see right there that is how you're going to be able to get the value for this and then if you want to be able to print that out on the screen Oh problem wrist mount print line what are we gonna do we're gonna print out the value of name which is going to be that private field we just got access to private field name paste that there I'll save and then execute it and there you are private field name 100 and we were able to get this right here say so you're able to use the reflection API to grab pretty much anything but definitely information whether it's private or not and like I said before you can do the same thing with private methods and also what's cool again is that all these method names can be passed as strings so just to prove that I'm going to go string and method aim is equal to and I'm going to type in get private like that and what am I going to do here here it is get private this is the method that I'm going to be accessing dynamically here so that's cool and if I want to access it while I'm accessing a method so I need to create a method and I'm just going to call it private method because that's what it is I'm gonna go equal UFO and on my ship because that is the object that I want to get hold of and I'm typing in class get declared method and then what I'm going to pass it well the name of the method that I want to execute or method name which is this guy right here see dynamically created with that string and it's really cool to be able to be able to do that and then I'm gonna pass it all over inside of here and there you are and what's it gonna do again it's gonna say hey guess what you need to catch yourself some more exceptions so I'm gonna come down through here and add catch Clause to surrounding try and there we are so I've got that set up again and now that I've defined that what am I have to do I'm gonna have to go private method and shut down the security on it so set accessible to true on that method and let's say that I also want to get the return value from a method I can just come in here and go string private return value cast that to a strength and then go private method invoke which is going to execute the method enemy ship private and then pass it all again I'll save it and then if I want it execute print out the return value from that private method system.out.print line and I'm gonna go enemy ship private method private return now and that gives me another error that says I need to add even more exceptions add catch clauses surrounding try say got that handle then we can file save it edie execute it and there you go enemy ship private method how did you get this there's the string if we jump over in UFO enemy ship dot Java you're gonna see this is the method that I called right there how did you get this so I accessed a private method called get private like I said I'm pretty much going to cover everything now what would you do if you want to execute a method that has parameters this gets a little bit more complicated but basically you're going to define the parameters expected by a private method now there's going to be more than one I'm just making this complicated just for the heck of it so it's going to be class or a that's going to have a whole bunch of different parameters so the first thing you need to do is go new and define the values of the parameters that are going to be sent so I'm going to send an integer and then you're going to have to follow that with type and then I'm gonna send a string which is a class so it's not a primitive it's an object and if we bounce over here again - UFO enemy ship you're going to see exactly what I'm doing here this is the private method that I'm going to be working with so it's private and I'm also going to show you how to pass parameters to it so again making is complicated just to cover everything there is enough then I want to provide the parameters above for those values so I'm going to create an object in this situation and I'm just going to call it params is equal to new object like this and then I type in new integer and I'm going to pass the value of 10 doesn't matter it can be anything of course and then new string and I have to pass a value and it's going to be random in this situation close that guy off and there you got that all set up so now that we've defined what parameter types we're going to send which is an integer string and we also define the values we're going to send which is a 10 and the string random now we got to get the method by providing its name and a class array with those parameters so I'm just going to use private method again because it doesn't matter I'm just going to do UFO enemy ship class get declared method and in here I'm going to define the name of the method remember you can do to have this by the dynamic can have it be a string that is provided but just to simplify things I'm not going to do it that way this time but there it is that's that name and then parameter types it's going to say well what type of parameters are you going to be sending to me well method parameters defines the type of parameters you're going to be sending so we're gonna copy then paste that down inside of there I like that and then what are we gonna do well we're gonna still enemy right get rid of that error okay now that's fixed and then we're going to shut down security for private method again true like that and then we're going to execute the method and pass parameter values for it so we're going to go it returned values with this cousin recalled this is going to be the return value sent from the method after everything has been executed so this is going to be a string private method invoke that means we're going to be executing a method which anim method or which method are we going to be executing well enemy ship private is the name and you can see that right here see here is enemy ship private it's just an object of type UFO enemy ship there's that guy enemy ship private and then the arguments that are going to be passed to it are going to be the actual parameter values which are stored in this object array called params so just going to paste that inside of there paste link and then if we want to output all of this information I know I hit you with a ton of things but you guys have been asking for an all-encompassing tutorial it covers everything so here you are you can watch it more than once if you didn't get it the first time but if you download the code you should be able to get most of this because it is very heavily commented and can be used like a cheat sheet sort of thing then we're just going to go private return Val which is what was passed after the method was executed file save and execute and it gave me an error that's just because I spelled parameters wrong so okay she told me about that so I have parameters spelled right both the hair as well as their file save it execute it and this time you can see everything was printed out so here is enemy ship other private method how did you get here and then prints out 10 and random and if we go to UFO enemy ship Java you're gonna see get other private method how did you get here and it's going to print out the integer and the string that you pass to it so there you go that's a ton of things you can do with Java reflection and the driver reflection API is a more app name feel free to leave any questions or comments below and in the next part of the tutorial I'm actually going to use the reflection API in a real world application way the next time
Info
Channel: Derek Banas
Views: 209,660
Rating: undefined out of 5
Keywords: Java Reflection Tutorial, Java Reflection Video Tutorial, Java Reflection
Id: agnblS47F18
Channel Id: undefined
Length: 28min 33sec (1713 seconds)
Published: Mon Sep 17 2012
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.