Database Reference
In-Depth Information
part of
setDecryptConns()
is to get a
byte
array from the
RAW
that we are calling
classInstance
. We feed
that
byte
array to a
ByteArrayInputStream
,
bAIS
. Then we instantiate an
ObjectInputStream
,
oins
,
coupled to
bAIS
. We call the
readObject()
method of
oins
to rebuild an
Object
named
classObject
. After
closing the streams, we get an instance of
Class
,
providedClass
for the
classObject
.
Listing 10-27.
Build a Class from a Byte Array
byte[] appClassBytes = classInstance.
getBytes()
;
ByteArrayInputStream bAIS = new ByteArrayInputStream( appClassBytes );
ObjectInputStream oins =
new ObjectInputStream( bAIS );
Object
classObject = oins.readObject()
;
oins.close();
Class
providedClass = classObject.getClass()
;
Use Java Reflection to Call Method
With the Class object, we can use
reflection
to get the name of the class and even to call its methods. This
is also part of
setDecryptConns()
method. Getting the class name is a single call to the
getName()
method. To call the
getRevLvl()
method in the inner class, we get a
Method
object,
classMethod
from
providedClass
by calling the
getMethod()
method, as shown in Listing 10-28. Then we call the
invoke()
method of
classMethod
, passing the
classObject
we got in Listing 10-27, to retrieve the actual return
value from
getRevLvl()
. Cast the return
Object
value as a
String
.
Listing 10-28.
Call Methods Through Reflection
String className = providedClass.getName();
Method classMethod
= providedClass.getMethod( "getRevLvl" );
String
classVersion
= ( String )
classMethod.invoke
( classObject );
// Do this once we get to Oracle
// Before we store any class, let's assure it has a package (.)
// noted before being an inner class ($) - our planned requirements
if( -1 == className.indexOf( "." ) ||
className.indexOf( "$" ) < className.indexOf( "." ) )
return "App class must be in a package and be an inner class!";
We are going to place some requirements on developers for their application inner classes. First, we
are going to require that their inner classes are declared
public
. We would also prefer that they are
declared
static
, but don't require that (however, it will be included in the template code we provide
them). Next, we require that they are inner classes and that their containing classes are contained in a
package. We can assure these requirements are met by assuring that the name of the inner class includes
a period, “.” character, indicating a package, and that it also includes a dollar sign, “$” character
sometime after the period, indicating an inner class of a class in a package. The javac compiler
concatenates the class and inner-class names, adding a dollar sign between them, to formulate the fully
qualified inner-class name.