1

Edit : do not read this i AM stupid :)


i have classes animal and dog

public class animal{
    public static String getTitle(){ return "bla"; }
}


public class dog extends animal{
    public static String getTitle(){ return "bla2"; }
}

when i do

animal p1=new animal();
animal p2=new dog();
System.out.println(p2.getClass().getDeclaredMethod("getTitle"));

i get

Main.java:16: unreported exception java.lang.NoSuchMethodException; must be caught or declared to be thrown
System.out.println(p2.getClass().getDeclaredMethod("getTitle"));

however if i do getDeclaredMethods getTitle is listed there.

am i stupid or just another reason to hate Java ?

3
  • 3
    That's just a compilation error and you've configured your IDE to run anyway regardless of the compilation errors. You might want to configure your IDE to not execute the code when it doesn't compile. Yes, you're stupid ;) Commented Mar 6, 2011 at 3:34
  • okay :) i am. but i guess after 50 tries to get the right result while each one littered the code more i wasnt thinking straight Commented Mar 6, 2011 at 3:41
  • 1
    u r not stupid at all if you have problems with the reflection api run-time checking. And don't hate Java, see dp4j.com for how not to have this problem in the first place! Commented Mar 6, 2011 at 7:03

1 Answer 1

2

You'll need to surround that statement with a try/catch block since it's using a cached exception. This essentially means that the compiler will ensure that you have some way of handling what happens in case an error occurs, to avoid an unfriendly crash screen shown to users.

In your case, you should do something like:

animal p1 = new animal();
animal p2 = new dog();
try {
  System.out.println(p2.getClass().getDeclaredMethod("getTitle"));
} catch(NoSuchMethodException e) {
  // error handling in the case getTitle() doesn't exit
}

If you don't want to handle the exceptions at all and prefer to just pass them on, without asking the compiler to check them, you can surround all your code in this:

try {
  // ...
} catch(Exception e) {
  throw new RuntimeException(e);
}

However, this is generally not good Java practice.

Sign up to request clarification or add additional context in comments.

2 Comments

The code above won't compile? Could you paste your compile error you're getting?
OH ! stupid me i was trying that earlier with getMethod when the methods were still private.... sorry for reacting so fast but i was very frustrated and you were right i had no more errors i just started reacting automatically (if(error){ rage++; trynextidea(); }) ^^

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.