M
Meidan
Hi all,
Can I execute programmaticlly the main of a class which I only the
..class file of?
Can I execute programmaticlly the main of a class which I only the
..class file of?
You can but do you really want to?Meidan said:Hi all,
Can I execute programmaticlly the main of a class which I only the
.class file of?
If you invoke Foo from a class called Bar, it will look like this:
Gordon said:Or even simpler:
Foo.main(args);
No need for an instance, constructors or reflection.
/gordon
BartCr said:Well, you'll need to make sure Foo is in the correct place in your
classpath when compiling
Meidan said:Hi all,
Can I execute programmaticlly the main of a class which I only the
..class file of?
But I didn't compile Foo, I only have the .class.
Well, you'll need to make sure Foo is in the correct place in your
classpath when compiling
Thomas said:But I didn't compile Foo, I only have the .class.
That's not a problem, all you need is the .class. But, it needs to be
in your classpath, so that the compiler can find it; the compiler needs
to see it so that it can check your code (e.g. to see whether or not
Foo contains a main() method, or else it won't be able to generate code
for the Foo.main() call).
Alternatively, use the reflection approach mentioned earlier:
try {
Class c = Class.forName("Foo");
String[] args = new String[] { "Hello", "world" };
Method m = c.getMethod("main", new Class[] { args.getClass() });
m.invoke(null, args);
} catch (Exception e) {
// Possible exceptions include ClassNotFoundException,
// NoSuchMethodException, InvocationTargetException
e.printStackTrace();
}
I get a java.lang.ClassNotFoundException when Class.forName("Foo")
is executed.
Can I execute programmaticlly the main of a class which I only the
.class file of?
Gordon said:So you've got classpath issues. Does "Foo" have a real name? Does it
belong to a package?
If so, the classpath should not point to the directory containing the
classfile. It should point to a directory containing a hierarchy of
directories that correspond to the component parts of the package name.
Learn more about the necessary relationship between the classpath and
the directory structure here:
http://www.yoda.arachsys.com/java/packages.html
Type "javap Foo" to see what the file contains if you don't already
know.
/gordon
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.