Java Reflection Explained - bɘniɒlqxƎ noiɟɔɘlʇɘЯ ɒvɒᒐ

Поделиться
HTML-код
  • Опубликовано: 10 июл 2024
  • Learn Reflection in Java! Break every Java rule with Reflection.
    Try Neeva FREE for 1 full month here! neeva.com/codingwithjohn
    00:00 Great Power of Reflection
    02:16 Getting Fields
    05:26 Setting Private Fields
    09:58 Getting Methods
    11:16 Invoking Methods
    15:58 Why Would You Use This?
    17:24 What Could Go Wrong?
    ☕Complete Java course:
    codingwithjohn.thinkific.com/...
    Reflection is one the more intimidating Java topics, because it can feel so confusing. But reflection isn't so tough once you learn the basics of how to do what you want to do. In this video we'll discuss the essentials of reflection in Java to get you started understanding how to bend Java to your will using it!
    Learn or improve your Java by watching it being coded live!
    Hi, I'm John! I'm a Lead Java Software Engineer and I've been in the programming industry for more than a decade. I love sharing what I've learned over the years in a way that's understandable for all levels of Java learners.
    Let me know what else you'd like to see!
    Links to any stuff in this description are affiliate links, so if you buy a product through those links I may earn a small commission.
    📕 THE best book to learn Java, Effective Java by Joshua Bloch
    amzn.to/36AfdUu
    📕 One of my favorite programming books, Clean Code by Robert Martin
    amzn.to/3GTPVhf
    🎧 Or get the audio version of Clean Code for FREE here with an Audible free trial
    www.audibletrial.com/johnclean...
    🖥️Standing desk brand I use for recording (get a code for $30 off through this link!)
    bit.ly/3QPNGko
    📹Camera I use for recording:
    amzn.to/3wlXcmR
    🎙️Microphone I use (classy, I know):
    amzn.to/3AYGdbz
    Donate with PayPal (Thank you so much!)
    www.paypal.com/donate/?hosted...
    ☕Complete Java course:
    codingwithjohn.thinkific.com/...
    codingwithjohn.com

Комментарии • 336

  • @CodingWithJohn
    @CodingWithJohn  Год назад +45

    Try Neeva free for 1 full month here! neeva.com/codingwithjohn
    There's no way I could fit everything you can do with reflection in one video. So here are some more things to try!
    Method stuff:
    Get a method's name:
    method.getName();
    Get a method's return type:
    method.getReturnType();
    Invoke a method:
    method.invoke(anyParameters, listedLikeThis);
    If it's private or not accessible, put this before it:
    method.setAccessible(true);
    See if a method has an annotation:
    method.isAnnotationPresent(NameOfAnnotation.class);
    Get an annotation from a method:
    method.getAnnotation(NameOfAnnotation.class);
    Get a method's parameter types:
    method.getParameterTypes();
    Get annotations on a method's parameters:
    method.getParameterAnnotations()
    Get the class that declares this method:
    method.getDeclaringClass();
    Get all exceptions the method declares it can throw:
    method.getExceptionTypes();
    Field stuff:
    Get the value of a field:
    field.get(objectToGetThisFieldFrom);
    Get the type of a field:
    Field.getType();
    Set the value of a field:
    field.set(objectToSetThisFieldOn, valueToSetTheFieldTo);
    Get the name of a field:
    field.getName();
    See if a field has an annotation:
    field.isAnnotationPresent(NameOfAnnotation.class);
    Get an annotation from a field:
    field.getAnnotation(NameOfAnnotation.class);
    Get the class that declares this field:
    method.getDeclaringClass();
    Class stuff:
    Get a class's name:
    class.getName();
    See if a class has an annotation:
    class.isAnnotationPresent(NameOfAnnotation.class);
    Get an annotation from a class:
    class.getAnnotation(NameOfAnnotation.class);
    Get declared fields:
    class.getDeclaredFields();
    Get all fields, which will include fields declared in parent classes:
    class.getFields();
    Get declared methods:
    class.getDeclaredMethods();
    Get all methods, which will include fields declared in parent classes:
    class.getMethods();
    This should get you started. Keep exploring to find out what more you can do!

    • @puneetkumarsingh1484
      @puneetkumarsingh1484 Год назад

      😂 0:54

    • @KhalilRahmouni-qe5zs
      @KhalilRahmouni-qe5zs Год назад

      no i use chatgpt instead

    • @ofekn
      @ofekn Год назад

      You pretty much skipped
      getField(String name)
      getMethod(String name, Class... parameterTypes)
      which are pretty useful

    • @lcgswolf
      @lcgswolf 18 дней назад

      Neeva is no longer existing! that is sad, I just heard about it

  • @Inkeri94
    @Inkeri94 Год назад +238

    you are without a doubt one of the best people teaching java and especially java core (I am already a working programmer but I like to watch well prepared videos as a way of knowgledge refreshment), keep up the good work man

  • @mushfiqfuad249
    @mushfiqfuad249 Год назад +141

    I can clearly say, John is by far the best Java tutor. I really wish him as my Java teacher back in my university days.

    • @carguy-xv2cl
      @carguy-xv2cl 9 месяцев назад +1

      Are you trying to say hes an old guy.

  • @davidx5828
    @davidx5828 Год назад +96

    John if possible could you do a video on Spring? Your through explanations would be beneficial to all.

    • @lcgswolf
      @lcgswolf 18 дней назад

      Yes please!!!!

  • @pebble6248
    @pebble6248 Год назад +7

    Your videos are great! I just got home from school, and without even finishing the video I've already shared it to my friend because (1) I know he'll benefit from it, and (2) I don't even have to finish it to know that it's amazing content.
    Thank you John!!

  • @vikingthedude
    @vikingthedude Год назад

    I am so grateful for these java tutorials. Not too beginner like a majority of tutorials out there, and very well explained

  • @Ross-sg3hq
    @Ross-sg3hq Год назад +6

    I've seen a lot of educational videos for Java but the way you explain stuff is a next level! Thank you :)

  • @armenuhiyeghoyan5419
    @armenuhiyeghoyan5419 Месяц назад +1

    I am from Armenia .I want to become a programmist.I like the way you explain.Simple and understandable.

  • @mattgraves3709
    @mattgraves3709 Год назад +17

    Hey John, I have been a software engineer for 12 years but I have a poor memory:) and appreciate your tutorials for my times revisiting concepts.
    I revisit even basic core concepts sometimes.
    As my career progresses, I find myself doing more code review and oversight vs coding myself plus I also use Kotlin (Android) half the time and trying to stay up on the latest language features and concepts as the industry changes is a lifetime of learning and sometimes relearning.
    You have a real knack at teaching and again, much appreciated 👍

    • @CodingWithJohn
      @CodingWithJohn  Год назад +8

      I'm in the same position where I rarely get to code myself anymore at my job. Kind of ironic that the better you get at coding the less you get to actually do it!

  • @DanielSColao
    @DanielSColao Год назад +1

    That's the best video regarding Java Reflection I've watched so far. Everything was clearly explained. Well done, mate.

  • @ByronicGuitarist
    @ByronicGuitarist Год назад +1

    Like a month ago I was reading some code at work that was doing reflection stuff and I thought to myself, "damn, I wish John had a Reflection video". Thanks John, you're the best in the game!

  • @Andrew94750
    @Andrew94750 Год назад +2

    I used reflection a year ago for AQA API client. John, huge thank you for this video! This video helped me to remember some things about reflection.
    It would a huge help to see a video about spring injection or SOLID.
    God bless you!

  • @TheGreat8220
    @TheGreat8220 Год назад

    I gotta be honest... This was the first RUclips video I've ever watched with a paid promotion that actually convinced me to look into the advertised item further. Also, I love all your videos!

  • @yuxiaofei3442
    @yuxiaofei3442 Год назад

    amazing video ,explain reflection thoroughly,so much easier understand than all the other guides out there on line

  • @pizz479
    @pizz479 Год назад

    Wow, this is such a fresh shock to me learning Java. I'm studying to switch my stack from Python to Java. Your lesson do help me a lot. Thanks for a good lesson John!

  • @user-pt9vi8gx6u
    @user-pt9vi8gx6u Год назад

    I am from Belarus and start to lern JAVA.I not so fine speak English, but you teaching very and very understanding. Thank you. I'm waiting for new lessons

  • @ObieR
    @ObieR Год назад

    Dude I cannot thank you enough for your incredible work. The way you break down these concepts make them so easy to understand. Would be amazing if could do a video about RX Java!!

  • @kenna5031
    @kenna5031 Год назад +17

    Reflection is a very powerful tool. I wrote an API to massively simplify the creation of command line user interface/interactivity for Java programs. I could not have done this without reflection (combined with custom annotations).

    • @cozyrain410
      @cozyrain410 Год назад +5

      this is cursed behavior

    • @beerensaft413
      @beerensaft413 Год назад +2

      if this API contains your code only why do you use reflection (your code is in front of you)

    • @makispapa5867
      @makispapa5867 Год назад

      @@beerensaft413 Using reflection you can have the user call java methods directly or modify fields etc via command line. With reflection you can create a more 'direct' scripting system enabling the user to access code directly from within the script. It's very useful.

  • @pikimk6167
    @pikimk6167 Год назад +4

    Some junior is lucky to have you as a mentor

  • @Devivl
    @Devivl Год назад

    You are without a doubt one of the best people teaching java! Thank you.

  • @ofekn
    @ofekn Год назад +1

    Here are some examples how reflections are used in real applications:
    events - using reflections and annotation you can build an event registry.
    equals - sometimes in the equals method, instead of using instanceof you use this.getClass() == that.getClass() this way you don't allow child classes to be equals.
    generics - when you use generics, you sometimes need the Class, for example Class#getEnumConstants can give you all possible values of an enum class, and Class#isInstance can help you verify fields.
    there is also java code which uses reflections, for example EnumMap has a constructor which accepts Class

  • @pradyumn2692
    @pradyumn2692 3 месяца назад

    Wunderbar. Maximum respect for explaining this in such a simple way

  • @maziarchoubineh7787
    @maziarchoubineh7787 Год назад +1

    Thank you very much for the complete narratives. Your videos have not only helped me with Java but also sparked my interest in becoming a developer.God bless you :)

  • @Msyoutube38
    @Msyoutube38 3 месяца назад

    By far the best explanation video I have seen on reflection. Excellent work, much appreciated!

  • @simonrozendal7542
    @simonrozendal7542 Год назад +1

    Hey John. I used reflection in my own framework architecture but less as possible, and there was no other option. I used it to for code in the future that doesn't exist yet. So thank you for your tutorial which confirmed is used it on a good way.

  • @GordonChil
    @GordonChil Год назад

    I have been using reflection (sparingly) for years. I never knew where the name came from until now. Thanks!

  • @rastkostajic5525
    @rastkostajic5525 4 месяца назад

    Mindblowing lesson!!! Never found this anywhere on the web. Thanks a lot.

  • @LTZMSYAL
    @LTZMSYAL Год назад

    Hey John you're the man! It's pleasant to watch your videos. I'm considering to subscribe to your java class.

  • @user-xq9cd5zb2r
    @user-xq9cd5zb2r Год назад

    you simply the best guide i've ever seen in java

  • @semilife
    @semilife 5 месяцев назад

    Wow thats powerful stuff, this is the first time I have tried to understand reflection in any detail. Thanks for a great video.

  • @mrphan529
    @mrphan529 Год назад

    the guidebook did, and now I finally understand the chanics!

  • @DipanjanPatra
    @DipanjanPatra Год назад

    I just gained a new superpower, this is an amazing introduction to reflections!

  • @WhitneyKugel
    @WhitneyKugel Год назад +5

    Thank you for this. You've given me a lot to reflect on.

  • @mightygreen3364
    @mightygreen3364 Год назад

    This is super interesting, I can especially see myself use this for testing classes

  • @inao-cz
    @inao-cz Год назад

    Really cool and nicely shown use of Reflections. For example, I've used this to autoload classes where I wanted and was lazy to write new Command(); 20 times.

  • @MD90X
    @MD90X Год назад +2

    you got me with the stack overflow bit.

  • @TheSeanUhTron
    @TheSeanUhTron Год назад

    I've never used reflections... But now that I learn a little bit more about it, I can see this being useful for debugging a running Java web application. JSP pages can be modified while the server is running, just like with PHP. So I could put some debug code with Reflections in it into one of those pages and mess with the main server code without having to recompile and redeploy!

  • @svalyavasvalyava9867
    @svalyavasvalyava9867 Год назад

    Wonderful content, as always. Thank you infinitely!

  • @jereramirez7433
    @jereramirez7433 Год назад

    Thank you! this was amazingly clear

  • @johnkeck
    @johnkeck Год назад

    Great explanation! Thanks, John!

  • @lucashenrique6076
    @lucashenrique6076 Год назад

    Thanks for the video John, always with a great explanation! It would be nice if you have commented about the use of reflections with Anotations and some example of it in a Framework.
    See ya!

  • @ollysalanson9452
    @ollysalanson9452 Год назад

    Thank you John!

  • @mihirgore4074
    @mihirgore4074 Год назад

    You just make eveything simple. Loved it. Do more videos :)

  • @charanko3760
    @charanko3760 Год назад

    I really love your contents! You explain very well. Hoping for more good contents ❤️

  • @adamlasry5225
    @adamlasry5225 Год назад

    Thank you for all your lectures.

  • @philippealexandredeleye4608
    @philippealexandredeleye4608 Год назад

    I love to use reflexion with annotation. It’s very powerful and you can easily save tone of time or help your junior dev to do repetitive or complex stuff easily.
    Like you said reflexion (also aop) it’s use on frameworks like spring and if they use it that a powerful tool that very interesting to use.

  • @Naimadmdp
    @Naimadmdp Год назад

    Nice video mate! And a great way to explain it too. Thanks for share your knowledge.

  • @davidl6797
    @davidl6797 Год назад

    Hi John, thank you for share knowledge!
    After a couple of time, I got to understand what reflection in Java means 😊

  • @Beee178
    @Beee178 Год назад +1

    Your videos are amazing, thank you!

  • @lalankeathauda7414
    @lalankeathauda7414 Год назад

    Thank you so much John, you are a great teacher.. If it's possible for you, please create a video on aspect oriented programming.

  • @sankalp.m.patilsmp1472
    @sankalp.m.patilsmp1472 Год назад

    Thank you for sharing these wonderful topics. You are the best Java tutor out there ❤️. Your explanation is very simple and easy to understand.

  • @Prashantable1
    @Prashantable1 Год назад

    Very well explained. Now my morning is good indeed.

  • @nischalofchrist
    @nischalofchrist Год назад

    This with your annotations video, and I totally understand how SpringBoot calls functions that you had defined with their annotations.

  • @SAED_212
    @SAED_212 Год назад

    I love your videos, thank you, its so much fun to try implement your videos' code into some of my projects

  • @ShermukhammadKarimov
    @ShermukhammadKarimov 2 месяца назад

    Thanks for clear explanation.

  • @idandrori
    @idandrori Год назад +3

    Always love some Better call saul references in my coding 😀

    • @CodingWithJohn
      @CodingWithJohn  Год назад +1

      Better Call Saul, Breaking Bad, Seinfeld - I sprinkle in whatever I can.

  • @princethampan
    @princethampan 4 месяца назад

    That was a cool simple and very useful tutorial. Thank you very much.

  • @AntonisKorezelidis
    @AntonisKorezelidis Год назад

    Great Explanation. Alot easier to follow than a professor.

  • @amallkrishna
    @amallkrishna Год назад +2

    Hello John! Your videos are quite helpful. Can you do a video on "Modules" in Java?

  • @ChrisBrown-dn3tf
    @ChrisBrown-dn3tf Год назад

    Hey John, it would be cool to see a tutorial about the java net package at some point. Most tutorials out there are very surface level, and a more in depth tutorial from you could go a long way.

  • @AntonyMBenedict
    @AntonyMBenedict Год назад +1

    I have never worked in Java, nor the need to do so (mostly C++/Python). I still watch your videos and enjoy them. You have a very good style. Do you have plans to teach C++ too? :D

  • @shubhamchouksey9904
    @shubhamchouksey9904 Год назад

    I must say that this is the first topic that I have already known before this video is being made 😅. Thanks for bringing this. Maybe it would better to have each design pattern in Java as a video

  • @dlandsvolka4046
    @dlandsvolka4046 Год назад +2

    16:08 IT'S REALLY USEFULL FOR SPIGOT PLUGIN DEVELOPER O_O
    now i can see and change the value of field and modify the game behavior

  • @foncki
    @foncki Год назад

    As usual mate, you’re a legend 👏 #keepCoding

  • @ruicsf
    @ruicsf Год назад

    Loving the videos! Would love to see a video on value objects if you get the chance :)

  • @christianmascolo2612
    @christianmascolo2612 Год назад +3

    Fantastic explanation,never heard about that. I loved the reference to better call Saul!

  • @anonimanonim1223
    @anonimanonim1223 Год назад

    BEST TUTORIALS EVER!!!!!!!!!!

  • @kbd3879
    @kbd3879 7 месяцев назад

    Cool Video Title man , i love your videos!!

  • @theredd1703
    @theredd1703 5 месяцев назад

    Your explanation is awesome!! Thanks!

  • @Gamer_with_knowledge
    @Gamer_with_knowledge 10 месяцев назад

    Hi John , by far you are the best java teacher I have found on youtube.
    I request you to start making videos on Spring-Boot topics as well.
    I swear views will skyrocket gradually.
    ~ Your faithful old subscriber.

  • @HocineFerradj
    @HocineFerradj 8 месяцев назад

    you are a good teacher !! thanks...

  • @AshankMishra
    @AshankMishra Год назад

    I cannot thank you enough for this🙏

  • @darjamilova5029
    @darjamilova5029 Год назад

    Perfect! Tnx a lot

  • @CallumAtwal
    @CallumAtwal Год назад

    A good use case for reflection is loading some class based on a string (of the package name) when you have multiple ones. Eg you might have to support something with multiple years. And you can use a year string to dynamically load a particular year class

  • @haltsmaul.
    @haltsmaul. Год назад +2

    Hey John, appreciate your videos as always.
    Since you covered Lambas already, wouldn't it make sense if you were to make a video on method references as well?

  • @user-do3df3rj5m
    @user-do3df3rj5m Год назад

    Thank you! You are wonderful teacher👍

  •  Год назад

    Thank you for your videos!

  • @stevanvieira3665
    @stevanvieira3665 3 месяца назад

    Great explanation, loved it, thanks :)

  • @JenHsingHuang
    @JenHsingHuang 11 месяцев назад

    So so so helpful, you are amazing

  • @user-md4mx4uq4q
    @user-md4mx4uq4q 9 месяцев назад

    Amazing! thank you

  • @robertoenriquechavezrodrig731
    @robertoenriquechavezrodrig731 Год назад

    Thank you man , amazing videos :)

  • @Kabasaurus
    @Kabasaurus Год назад

    Great explanation, thanks you so much on helping me on my studies :)

  • @neon0wl2107
    @neon0wl2107 Год назад +2

    Wow, ok this is the first time i have watched the whole promotion on any video. I just realized this.

  • @daliaabdou4147
    @daliaabdou4147 Год назад

    awesome explanation, thank you

  • @MrAikien
    @MrAikien Год назад

    Wow! This is awesome! Thanks! 👌👍🙏

  • @saahilnayyer6865
    @saahilnayyer6865 Год назад +2

    The Better Call Saul reference really put a smile on my face. Nice cat name. Haha

  • @mahoneg
    @mahoneg Год назад +11

    As a long-time programmer in many languages, I still love watching your videos. I recommend them to jr developers as well. Warning ** Don't use something just because it seems cool***. Keep it simple and straightforward if you can. It will be easier for you and the people who follow you into your code. I am more of a dog guy but I like cats too!

    • @CodingWithJohn
      @CodingWithJohn  Год назад +7

      Awesome, thanks for recommending them! And you're right. Reflection or otherwise, opt for simplicity, readability, and maintainability over coolness. Though it's fun to know the cool stuff too.

  • @aniketnangare904
    @aniketnangare904 10 месяцев назад

    Thanks a lot for this great knowledge

  • @ohno2125
    @ohno2125 Год назад +1

    At first, I have thought setting private fields was for security reasons (as even my university professor once told me 'if possible, make every method private for security reasons') when regarding to Java programming, how wrong am I now that I've watched this video, that is not the case (and I see why how we can use this as you've explained). Thanks for the information!

    • @CodingWithJohn
      @CodingWithJohn  Год назад +2

      That's typically still a good idea! But yeah you're still able to break basically every rule with reflection

  • @surajverma-ut4kj
    @surajverma-ut4kj Год назад

    Hey John, really loves your explanation.
    You say you will post every week, but I am still waiting for your new video!!
    Kindly explain SpringMVC, DAO class.

  • @umabharathyts1998
    @umabharathyts1998 21 день назад

    Thank you so much 🙏

  • @mehulsolanki9435
    @mehulsolanki9435 10 месяцев назад

    You are too good to be true! I can learn anything you teach!

  • @mrugankgadgil7368
    @mrugankgadgil7368 Год назад +4

    John - can you make something on DSA using Java. Nowadays DSA is one of the hot topics.
    Topics like dynamic programming (top down & bottom up),
    Stacks,
    Queues,
    Linkedlist,
    Trees,
    Graphs,
    Greedy algos,
    Backtracking,
    Sliding window,
    2 pointers
    I know that's huge but an understanding on the concept by using your teaching techniques would definitely benefit.

  • @robert202
    @robert202 Год назад

    Hello John, I have been watching you since I started early this year. I have learned so many things from you because you make things simple. Could you please make a tutorial about java lambda expressions: how to use it and when to use it. Thank you very much!

    • @CodingWithJohn
      @CodingWithJohn  Год назад

      Hi Robert! I do have this video on the subject of lambdas: ruclips.net/video/tj5sLSFjVj4/видео.html

  • @tarikuasfaw6405
    @tarikuasfaw6405 Год назад

    Thanks John you're really nice

  • @isaacwhiz
    @isaacwhiz Год назад

    You are really a coding geek. Thank you

  • @cerealhit555
    @cerealhit555 9 месяцев назад

    God I LOVE YOUR VIDS. I had somewhat of a hard time to understand reflection but now it's clear as ever.

  • @edgbaston149
    @edgbaston149 Год назад +1

    Thank you so much

  • @sandeeproy7621
    @sandeeproy7621 8 месяцев назад

    Thank you.

  • @user-jp5uu6de2n
    @user-jp5uu6de2n 5 месяцев назад

    Hi John. I am Ukrainian, my English is so so. But thank God I understand almoust all your speaking. Short and easy to understanding. Thank you Bro.