Check if a variable exists in a class

Asked

Viewed 242 times

0

People I am trying to verify if a variable exists in a class. For this I am using the code:

try{
    clazz.getDeclaredField("id");
} catch(Exception e){
    System.out.println(e.getMessage());
}

With that I can see without problems.

My Problem: When the variable does not exist java prints in the console the name of the variable that does not exist, I need this information not to appear if the variable does not exist. how do I not do this? some can give me a light?

EDIT: even if I remove System.out.println(e.getMessage()); it keeps printing the name of the variable that does not exist, this is what I do not want to appear

  • If you put the print inside the catch does not work?

  • actually that’s what’s going on, the system launches in the console the print, and I need to take it out. Maybe I got a little confused

  • 1

    Hello. I think your problem goes beyond the code snippet. The fact that you mentioned that Java still prints something even after it is removed probably means that you are not running the same version of the code that you are editing. It may be that the compiled file is outdated, for example, what happens if your editor does not compile or is not configured to automatically compile the changed classes. Before trying more advanced things, I suggest you first try to better master the environment in which you are developing to avoid frustrations and inconsistencies like this in the future.

1 answer

0


Are you sure you don’t want to do anything if the variable doesn’t exist? This is probably a programming error and should be fixed. Exception does not serve for this.

If you want to insist just print anything:

try {
    clazz.getDeclaredField("id");
} catch(Exception e) {}

I put in the Github for future reference.

  • no, I just need to do something if it exists, my problem is that java is printing on the console the variable if it doesn’t exist, and I don’t want it to print, not need it, adding, even taking out System.out.println(e.getMessage()); it’s printing

Browser other questions tagged

You are not signed in. Login or sign up in order to post.