Java Reference
In-Depth Information
e
.
printStackTrace
();
}
catch
(
IllegalAccessException
|
InvocationTargetException
x
)
{
x
.
printStackTrace
();
}
However, it should be pointed out that reflection always involves unknown inforā
mation. To some degree, we just have to live with some of this verbosity as the price
of dealing with reflective invocation, and the dynamic, runtime power that it gives
to the developer.
As a final example in this section, let's show how to combine reflection with custom
classloading to inspect a class file on disk and see if it contains any deprecated
methods (these should be marked with
@Deprecated
):
public
class
CustomClassloadingExamples
{
public
static
class
DiskLoader
extends
ClassLoader
{
public
DiskLoader
()
{
super
(
DiskLoader
.
class
.
getClassLoader
());
}
public
Class
<?>
loadFromDisk
(
String
clzName
)
throws
IOException
{
byte
[]
b
=
Files
.
readAllBytes
(
Paths
.
get
(
clzName
));
return
defineClass
(
null
,
b
,
0
,
b
.
length
);
}
}
public
void
findDeprecatedMethods
(
Class
<?>
clz
)
{
for
(
Method
m
:
clz
.
getMethods
())
{
for
(
Annotation
a
:
m
.
getAnnotations
())
{
if
(
a
.
annotationType
()
==
Deprecated
.
class
)
{
System
.
out
.
println
(
m
.
getName
());
}
}
}
}
public
static
void
main
(
String
[]
args
)
throws
IOException
,
ClassNotFoundException
{
CustomClassloadingExamples
rfx
=
new
CustomClassloadingExamples
();
if
(
args
.
length
>
0
)
{
DiskLoader
dlr
=
new
DiskLoader
();
Class
<?>
clzToTest
=
dlr
.
loadFromDisk
(
args
[
0
]);
rfx
.
findDeprecatedMethods
(
clzToTest
);
}
}
}