Type casting to a class known only at runtime?

How would one go about type casting an object to a class that is loaded at runtime via a class loader?

I currently load an serialized instance of the run-time known object from a file and so i need to cast to the run-time known object before i can use it.

Use reflection. java.lang.reflect.* IIRC.

Might be simpler than that, blah. Moogie, you are deserializing one of your objects, and the reference you are passed is an Object? If you know what the type is, and you can “hard code” it, a simple cast will do the job:

Object theObject = deserializeMyObject();
if(theObject instanceof MyClass)
{
  MyClass myClass = (MyClass)theObject;
  myClass.myMethod();
}

If you can’t use the name of the class in the source code (don’t know anything about the class ahead of deserialization) then yes, you’ll need to use Reflection to inspect the class members and manipulate them with Field and Method objects - see the java.lang.reflect package as mentioned above.

Ah, i thought there might be a nice easy way of doing it via templates… guess not.

cfmdobbie, It is highly possible that the program will not know the class to cast to and as such will request the appropriate class via a custom class loader.

hmm, i will havet to read up on my reflection me thinks!

thanks anyway guys!

What kind of classes are you loading?
Maybe you could define an interface which those classes should implement. Then you can cast it to that interface.
I was thinking that probably your program must know something about the classes being loaded in order to use them.

[quote]What kind of classes are you loading?
Maybe you could define an interface which those classes should implement. Then you can cast it to that interface.
I was thinking that probably your program must know something about the classes being loaded in order to use them.
[/quote]
The classes at the moment inhert from a common super class. would it be sufficent to cast to that super class? even if the sub class may contain other methods?

It sounds like you really need to learn about interfaces (as in the java keyword, unfortunately a common word in programming :)).

“interface” in java IMHO (others here disagree :)) is really a synonym for “abstract datatype”, i.e. it lets you define new types in java.

So, what erikd is suggesting is that you create a new type of your choosing (by writing an interface) and make all your imported things of that type.

e.g. if you are loading modules you might create a “module” type which is defined as always having a “getName” method. When loading the modules, you would typecast them directly to “module”


module importedModule = (module) myMethodToImportAModule();
System.out.println( "imported module = "+importedModule.getName() );

Although convention says you should call it Module instead of module :).

I do understand interfaces in java. The super class i am currently using can probably be redesigned to be an interface as there is little program logic in the superclass… i’ll just make sure the classes that use the interface include that logic.

What i did not know is that you could type cast to an interface… you learn new things every day :slight_smile:

I will give that a go.

Seeing as the program does not know what the class will be in advance, it can’t very well call any methods on it can it? So it’s an Object whatever way you look at it.

If you’re expecting to be able to call methods on it, create an interface that exposes these methods and cast it to that.

Cas :slight_smile:

Good point. This is the kind of thing that I find is helped if people learn from the start that interface == ADT. If you start off thinking of it as a full type, then you more naturally assume it is typecastable :)…

Agreed - the day I realised I could directly refer to a reference of interface type was a happy, happy day.

Converting everything to use interfaces isn’t actually necessary - you can still use your superclass:

SuperClass myClass = (SuperClass)getSerializedThingy();
myClass.myMethod();

But whichever way you do it, methods that aren’t declared in the superclass/interface cannot be accessed via that reference - you’ll still need to cast the object to the specific class if you want to use them.

But that’s okay - if you know you need to call a certain method, you know what class you expect your reference to be, so can cast it!

thanks for all the help!

the world would be a better place if we could progamatically load and add classes to the default classloader at run time so that we need not do anthing extra to use the classes. but i am sure the ambiguity is what is stopping this from happening.

But once you deserialise your object and cast to a subclass, it’s just the same as any other object in your application. There’s no “compile time” versus “run time” difference if you can do that cast. If you really don’t know enough to make that cast, then in the absence of a class definition you’ll have to go through a reflection system - that’s no failing of the classloader.

I think you may have the wrong end of the stick somewhere - maybe you’d better just post the code you’ve currently got and describe what you’re trying to do, and we’ll see what we can suggest? I suspect a bit of rearchitecting may be in order.

I belive that what you have suggested will be sufficent. I will not be able to program the changes until Wednesday but i am confident that it will work.

I am programing a distributed network architecture for intelligent sensor agents.

The problem i am trying to resolve is the fact that some agents request a command to be performed on another agent in the network who potentially does not have the code to perform the command. In this case the target agent will request the appropriate code from the other agent (i.e. a class) it loads this via a classloader.

As well as being asked to perform a command, serialized objects are sent to the target agent which then will be passed as parameters to a method in the command.

Since i now know that i can type cast to an interface i shold be able to run that method.

hmm… thinking just now… what happens if the command loaded via the class loader internally type casts to classes unknown? (or loaded via the classloader) will it have a run-time error if so can i get around it?

thinking some more…

I will be able to catch the exception if the class loaded via the classloader creates a new object of unknown type and then handle it.

Interfaces wouldn’t be much good for anything if you couldn’t reference an object as it’s interface type.

How unknown are the classes you are loading, and more importantly, is there a lot of different possibilities? If there are only a few possible classes being loaded then you could use instanceof to determine what to cast the class to… but if it’s loading classes based on something that is typed in by the user or from a file that’d be different.

The classes can be, by design and nature, radically diverse. The only common attributes about the classes being loaded is that they (at the moment) extend from a common super class and that they all will implement a method called process with the signature:

public Object[] process (Object[] arg)

the arg object array is an array consiting of serialized objects and the return object array will contain the results of the processing.

Sounds like a job for an interface to me.

[quote]The classes can be, by design and nature, radically diverse. The only common attributes about the classes being loaded is that they (at the moment) extend from a common super class and that they all will implement a method called process with the signature:

public Object[] process (Object[] arg)

the arg object array is an array consiting of serialized objects and the return object array will contain the results of the processing.
[/quote]
If that is the one method you need to call, you can define an interface with that method and cast to the interface.
If there are other methods, do you know beforehand what other methods you need to call? I would guess so, and you could interface to those as well.

The only method that is required of the loaded class is the process method. Loading a class and type casting it to the interface is not a problem… the problem is that this loaded class may use classes unknown to the current class loader… how would i go about loading in classes required by this loaded class?

maybe it is not as difficult as i seem to make it out to be… which classloader will be used by the runtime environment when trying to load/find classes that are used in the loaded class? If it is the classloader that actually loaded the class then i should be able to modify my classloader implementation else if it is the default classloader i believe i may be in trouble… unless i can set the default classloader to be my own.