Jump to content

Reflection help.

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
2 replies to this topic

#1
Skel

Skel

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
Could someone tell me what i'm doing wrong with here please:

 public static void run(String name) {

 		try {  			

 			System.out.println(name);

 			Class s = Class.forName(name); 			

 			Method m = s.getMethod("start");

 				m.invoke(s.newInstance());

 	} catch (Exception ex) {

 	}

 		

 	}

I'm trying to run a method from another class.

name = path of the class im running.

It prints out the name, as I told it to, but it doesn't seem to run the method i'm telling it to.

Thanks.

#2
morefood2001

morefood2001

    Speaks fluent binary

  • Members
  • PipPipPipPipPipPipPipPip
  • 1,720 posts
That is because you are trying to instantiate a class, Method.

You should remove "Method m = s.getMethod("start");" entirely. s.invoke should do the trick.

For example (I didn't test this in a compiler, so there may be an error or two):

public class hi {
public hi(){
//do something
}
public method{
//do something
}
 public static void main(String args[]) {
 				
 			System.out.println(name);
hi h = new hi();
h.method(); //calls method in hi 			 	
}		
}


#3
Skel

Skel

    Learning Programmer

  • Members
  • PipPipPip
  • 33 posts
Fixed, and thanks for trying ^^ but that wouldn't have solved it.