So I'm creating a game that I want to be able to add more characters in without recompiling the whole thing. Is there a way java automatically detects classes or is there a way I can access a class at runtime by a string so that I can just read a text file and know what classes to get?

If so, can you guys give me links to sites that may help?

Thanks

Recommended Answers

All 5 Replies

Is there a way java automatically detects classes

yes, kinda, depending on what you mean

is there a way I can access a class at runtime by a string so that I can just read a text file and know what classes to get

yes

You can set up a directory and have your application scan that for jarfiles, then use a special classloader to load classes from any jarfiles it finds there.
Such classloaders exist but you'll have to look for them (or write your own).

Use reflection to load classes by name.

Isn't there something in standard library for this?

I just noticed a class called ClassLoader and I was wondering how you'd use it. It's abstract, so I'm a little confused about using it. Can someone show me an example of how to use it?

So lets say I have Bob.class with a constructor Bob(). After getting the String Bob, how would I load the class at run time and construct an object Bob?

Isn't there something in standard library for this?

Everything jwenting listed is in the standard library.

I just noticed a class called ClassLoader and I was wondering how you'd use it. It's abstract, so I'm a little confused about using it. Can someone show me an example of how to use it?

So lets say I have Bob.class with a constructor Bob(). After getting the String Bob, how would I load the class at run time and construct an object Bob?

Google for some ClassLoader tutorials/examples. You should be able to find a whole lot of them.

While your at it, Google for reflection tutorials, as well, as that will also play a big part.

Once you have some code, almost regardless of how much, and cannot advance any further, come again, post that code, state your problem (clearly and concisely), include any supporting info (i.e. compile and/or runtime exceptions), and we can help you further.

Check out this code snippet, it loads some class files and shows an example of loading a resource (directory or jar file) and then looking for a specific class in it. It uses URLClassLoader (one of the standard impl of ClassLoader), you'll find more implementations if you don't wanna write own.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.