简体   繁体   中英

how to check return type of method is JLabel

Could anyone help me find to check return type of a method is of specific type in JAVA. I tried this. But unfortunately it doesn't work. Please guide me.

Field[] fields = LanguageTranslation.class.getFields();

    for(Field f : fields ){
    System.out.println("Type is:"+f.getType()+"\t Name:"+f.getName());
      if(f.getType().equals(JLabel))
       {
                System.out.println("Field is of type "+f.getType());
             //other stuff
        }

Here f.getType() returns an object, I want to check weather it is a JLabel or not. If it is, I have other stuff to do. I tried above code , error is JLabel cannot be resolved to a variable I have declared one JLabel in class as public JLabel testingText=null; please help me in this

You can use instanceof to find out of which type an object is. But as you're using reflection, you first need to get the value of the field inside the object which you want to reflect. Example:

LanguageTranslation translation = ...; // Your object
Field[] fields = LanguageTranslation.class.getFields();

for(Field field : fields ){
    Object fieldValue = field.getValue(translation);

    if(fieldValue instanceof JLabel) {
        System.out.println("Field " + field.getName() + " of translation " + translation + " is a JLabel!");
    }
}

I never suggest you to use Reflection instead use getter method to access field directly.

If still there is no option other than Reflection then try

f.getType().getName().equals(JLabel.class.getName())

Read more...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM