Welcome to my Java Reflection Video Tutorial! I’ve been asked many times to cover Java Reflection lately and in this tutorial I’ll show you pretty much everything you can do with Java Refelection.
Many people are confused by reflection because they think it is a concept or technique. Java Reflection is an API and as soon as you know that it becomes easy. The Java Reflection API is used to manipulate classes and everything in a class including fields, methods, constructors, private data, etc. And, in this tutorial you’ll learn it all!
If you like videos like this, it helps if you tell Google [googleplusone]
Sharing is great as well [nttfblike]
Code from the Video
I used a class I previous used in my Abstract Factory Design Pattern tutorial. I provide it here with the changes made in the video, but you should also get the code on that page to get everything to work.
UFOEnemyShip.java
TestingReflection.java
This is Awesome.
Everything works 100%,
There is a minor thing I have just noticed for the first time. Which is the possibility of creating instance of object that take argument, it is possible for that argument to be a reference refer to null;
//line 151
EnemyShipFactory shipFactory = null;
//line 157
newEnemyShip = (UFOEnemyShip)constructor.newInstance(shipFactory);
Thank you Derek.
Thank you very much 🙂 I always wanted to solve all of the confusion around reflection. I covered questions I’ve received on reflection in my interpreter design pattern tutorial as well. I hope it helps.
Derek,
I went through a few of your videos. What you have here is a treasure trove. Your style is very unique. I have to admit though these may not be for beginners. But if one has a basic understanding of the subjects, the stuff you have will take him/her to the next higher level in no time.
Thanks for the enormous effort you have put in.
You’re very welcome 🙂 Thank you for the kind compliments. Yes, I don’t aim to have mass appeal. I look to instead either cover topics that most people ignore, or present information in completely different ways. I’m glad you like them
Hey Derek
You have a typo in your code.
line 3 in UFOEnemyShip class you have idcode ‘c’ in lower case but in your TestingReflection you use “idCode” upper case just thought i mention in case anyone wonders why it wasn’t working. other then that. Thanks for the lesson.
Thanks Derek,
U explained reflection in a very easy way . My confusion about reflection is resolved now .
🙂
I’m very happy that I could help 🙂 You’re very welcome.
Thanks for the lesson, this is the first time i understood it. I have one doubt could you please let me know the practical use case of reflection.
Thanks in advance
You’re very welcome 🙂 I’ve found reflection is very good for testing code. In the research world it is sometimes very beneficial to take advantage of its dynamic capabilities. You can also use it to by pass private, protected, etc. Again this is done for analyzing a class rather then for use in real world code.
Is it not the case that line 149 and 151 sort of self defeating?
You have explicitly typed the names of the classes. I would think the whole point of the excersize is to not know the absolute names of any classes. All names need to be got at runtime.
With looking at your example I can build the following code that DOES NOT need have fore knowledge of the actual classnames.
package com.pat.example2;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestReflection2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(“TestReflection2”);
Class myruntimeclass=null;
try {
myruntimeclass= Class.forName(“com.pat.example2.MyRunTimeClass”);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// create the object with the default constructor
Object myruntimeclassobj = null;
Field f=null;
try {
myruntimeclassobj = myruntimeclass.newInstance();
// object constructed now find a set method with parameter of a string
Class c;
c = myruntimeclassobj.getClass();
String s1;
s1 = doSet(c,myruntimeclassobj,”hellopatty”);
System.out.println(“afterset>”+s1+””+s1+””+s1+””+s1+””+s1+”<");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// object constructed now find a set method with parameter of a string
System.out.println("exiting");
}
public static String doGet(Class c, Object obj) {
String sRes =null;
Method[] m;
m = c.getMethods();
for(int i = 0;i<m.length;i++)
{
if(m[i].getName().matches("Get"))
{
try {
sRes = (String)m[i].invoke(obj);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return sRes;
}
public static String doSet(Class c,Object obj ,String s)
{
String sRes =null;
Method[] m;
m = c.getMethods();
for(int i = 0;i<m.length;i++)
{
if(m[i].getName().matches("Set"))
{
try {
sRes = (String)m[i].invoke(obj, "hellopatty");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return sRes;
}
}
————-
package com.pat.example2;
public class MyRunTimeClass {
public MyRunTimeClass()
{
System.out.println("ctor:no values passed");
}
public MyRunTimeClass(String s)
{
System.out.println("ctor with string");
snam = s;
}
private String snam="NOTSET";
public String Set(String snam)
{
System.out.println("stringin"+snam);
this.snam = snam;
return this.snam;
}
public String Get()
{
System.out.println("stringout"+snam);
return this.snam;
}
}
The main routine came over wrong on the paste:
— try againg —package com.pat.example2;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class TestReflection2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(“TestReflection2”);
Class myruntimeclass=null;
try {
myruntimeclass= Class.forName(“com.pat.example2.MyRunTimeClass”);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// create the object with the default constructor
Object myruntimeclassobj = null;
Field f=null;
try {
myruntimeclassobj = myruntimeclass.newInstance();
// object constructed now find a set method with parameter of a string
Class c;
c = myruntimeclassobj.getClass();
String s1;
s1 = doSet(c,myruntimeclassobj,”hellopatty”);
System.out.println(“afterset>”+s1+””+s1+””+s1+””+s1+””+s1+”<");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// object constructed now find a set method with parameter of a string
System.out.println("exiting");
}
public static String doGet(Class c, Object obj) {
String sRes =null;
Method[] m;
m = c.getMethods();
for(int i = 0;i<m.length;i++)
{
if(m[i].getName().matches("Get"))
{
try {
sRes = (String)m[i].invoke(obj);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return sRes;
}
public static String doSet(Class c,Object obj ,String s)
{
String sRes =null;
Method[] m;
m = c.getMethods();
for(int i = 0;i<m.length;i++)
{
if(m[i].getName().matches("Set"))
{
try {
sRes = (String)m[i].invoke(obj, "hellopatty");
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return sRes;
}
}
Still the code is going over incorrectly. Regardless I use the invoke method and can design a runtime call to access a class for a bluetooth rfcomm interface on android.