Check out more great lessons via this link:
http://coderscampus.com/blog
If you’ve ever used the JavaScript language before, you might be familiar with
the eval() function.
If you’ve never used JavaScript before, then no worries, I’ll have an in-depth
explanation as to what’s going on.
For you JavaScript coders out there, the eval() function is used so that you can
write any strings you like inside of the function, and the JavaScript engine
will interpret it and run it like it was native JS code.
This “execution of code written out as Strings” concept is very similar to what
reflection in Java accomplishes.
Reflection in Java is a way to call the methods of objects without needing the
actual reference to those objects.
Another way to say it is, you can programmatically execute methods with
reflection in Java.
Getting Started with Java Reflection
So, one of the keys to working with reflection in Java is to make use of the
Method class.
The Method class gives us access to some cool stuff… Namely the ability to
“invoke” methods that you want to have invoked (programmatically).
Let’s assume you’ve got a standard Java class that has some getter and setter
methods like so:
public class User
{
private Long id;
private String email;
private String password;
public Long getId()
{
return id;
}
public void setId(Long id)
{
this.id = id;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getEmail()
{
return email;
}
public void setEmail(String email)
{
this.email = email;
}
}
The User above is a super common Java bean that represents some user.
You’ve seen what it looks like to “invoke” any of these methods. For example, if
we wanted to invoke the getter method for a User‘s email, it would be:
// Let's assume we can load a user from the database by ID like so:
User aUser = userRepository.findOne(1L);
// now we invoke the getEmail() method to get the email address of user with ID
1.
String userEmail = aUser.getEmail();
Nothing fancy going on here (assuming you know what a repository is, if you
don’t I’d recommend reading about it here)
So now let’s introduce Java reflection.
Here’s that same code, only now we’ll invoke the getter method using
reflection:
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
User aUser = userRepository.findOne(1L);
try
{
Method method = aUser.getClass().getMethod("getEmail");
String userEmail = (String) method.invoke(aUser);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException e)
{
// If your code makes it in here, you're likely having an issue with one of the
following:
// 1. Your method name is incorrect / doesn't exist on the User class
// 2. The method exists, but when Java tried to invoke it, you didn't pass the
right object to invoke the method on
// 3. The method exists and you passed the right Java object, but you didn't
give it the correct method signature (i.e. you didn't pass in the right types
for the parameters.
e.printStackTrace();
}
Naturally it takes more code to make reflection do its thing, namely in the
number of exceptions that need handling.
But the “business-end” of the code really comes down to two things:
Assigning a Method variable with the appropriate method you wish to invoke
Invoking the method
The first step is accomplished by first getting the appropriate class with which
you’d like to work: aUser.getClass(). Then once we have the class we’d like to
work with, we can locate the method we’d like to invoke via the getMethod()
method.
Very meta.
The most important thing to note here is that the process of “getting a method”
via the getMethod() method takes a String as an argument.
This means that you can pass in a String variable to this method… This means
that the process of “getting” a method and invoking it can be completely dynamic
and can change at run-time.
This is the whole reason why Ja
Nesta página do site você pode assistir ao vídeo on-line EP08 – Java Reflection – Writing Generic Java Code duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário Coders Campus 13 Abril 2017, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 352 vezes e gostou 0 espectadores. Boa visualização!