[java] How do I call a method in java when I don't know what it is beforehand?

Started by
18 comments, last by Shaggy999 22 years, 2 months ago
What about loading .class files and creating objects during runtime?
Advertisement
Btw, since this post is really old it might be worth mentioning that Wayfarer''s statement about reflection being slow might not necessarily be true anymore. At least Sun propaganda claims that parts of the reflection mechanism have been reimplemented in JDK1.4 and that method calls through reflection are now 20 times faster than they were in JDK1.3.1.
The java.lang.Class.forName(String className) method will load classes for you and return java.lang.Class objects. To instantiate objects from those classes you just call the newInstance() method on them. This should all work fine if your classes are stored in .class files located in your class path. If you want to load classes in other non-standard ways, you might have to write your own class loader.
Thanks

Does java have a method similar to C''s system() function? If it does, I might try using javac while the game is running.
From java.lang.Runtime

    Runtime r=Runtime.getRuntime();//dont forget to put the full path in the exec stringProcess p=r.exec("javac MyClass.java");try {  //wait for the process to end so you don't try to  //load the class before it is compiled  p.waitFor();}catch (InterrupetedException e) {  System.out.println("exception:"+e);}//EDIT: don't forget to check that it compiled correctlyif(p.exitValue()==0) {  //load the class}  

You can then use java.lang.ClassLoader to load the class.

---
Make it work.
Make it fast.

"Commmmpuuuuterrrr.." --Scotty Star Trek IV:The Voyage Home

Edited by - CaptainJester on February 7, 2002 9:24:03 AM
"None of us learn in a vacuum; we all stand on the shoulders of giants such as Wirth and Knuth and thousands of others. Lend your shoulders to building the future!" - Michael Abrash[JavaGaming.org][The Java Tutorial][Slick][LWJGL][LWJGL Tutorials for NeHe][LWJGL Wiki][jMonkey Engine]
Thank you!
Why create your own scripting language when there''s already a good one out there?

www.jython.org

sites about scripting languages that run in a JVM
http://www.byte.com/documents/s=505/BYT20001214S0006/
http://www.ociweb.com/jnb/archive/jnbMar2001.html
http://www.mindview.net/Books/TIPatterns/index_html
I did consider using jython, but it doesn''t seem to be very well documented, and my attempt at embedding it failed miserably.

How do you access an java object within a python script?
Instead of calling a system javac, you could also use a java compiler written in java ! IIRC there was one on sourceforge, but can''t remember the name :/
I think BeanShell can be used for scripting. Not sure how it works though.

This topic is closed to new replies.

Advertisement