Link to home
Start Free TrialLog in
Avatar of mitchguy
mitchguy

asked on

Dynamic casting using reflection

I'm trying to set the values of JLabels via label.setText( ), where the value is the result of a function call, which in my application
is unknown, because it's done using relflection and the invoke function call. The invoking part works and
I can cast the value to see that in the JLabel, by cheating because i know what type i'm looking for just to test it.
But in my application i won't know what type to cast it to, so i'm trying to do the cast now using reflection and
not having very much luck. Here is the compile error I'm getting for an example program given in the code below.

I also don't know how to handle or if it is even possible to handle enums as a type?
I'd like to add that to the example program below. I will be using some classes that I didn't create
and there are enums in them.


ReflectionTypesTest.java:119: setText(java.lang.String) in javax.swing.JLabel cannot be applied to (java.lang.Object)
          myBoolLabel.setText(boolClass.cast(typesObj.getMyBool()));
                     ^
ReflectionTypesTest.java:120: setText(java.lang.String) in javax.swing.JLabel cannot be applied to (java.lang.Object)
          myIntLabel.setText(intClass.cast(typesObj.getMyInt()));
                    ^
ReflectionTypesTest.java:121: setText(java.lang.String) in javax.swing.JLabel cannot be applied to (java.lang.Object)
          myDoubleLabel.setText(doubleClass.cast(typesObj.getMyDouble()));
                       ^
3 errors








import java.lang.reflect.Field;
import java.awt.*;
import javax.swing.*;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;

public class ReflectionTypesTest {
    JFrame myFrame;
    public static JLabel myBoolLabel;
    public static JLabel myIntLabel;
    public static JLabel myStringLabel;
    public static JLabel myDoubleLabel;
    public static JLabel myEnumLabel;
   
    TitledBorder titleBool;
    TitledBorder titleInt;
    TitledBorder titleString;
    TitledBorder titleDouble;
    TitledBorder titleEnum;
   
    public ReflectionTypesTest() {
        myFrame = new JFrame("DynamicCasting");
        myFrame.setSize(new Dimension(200,200));
       
        titleBool = BorderFactory.createTitledBorder("myBool");
        myBoolLabel = new JLabel("init string");
        myBoolLabel.setBorder(titleBool);
       
        titleInt = BorderFactory.createTitledBorder("myInt");
        myIntLabel = new JLabel("init string");
        myIntLabel.setBorder(titleInt);
       
        titleString = BorderFactory.createTitledBorder("myString");
        myStringLabel = new JLabel("init string");
        myStringLabel.setBorder(titleString);
       
        titleDouble = BorderFactory.createTitledBorder("myDouble");
        myDoubleLabel = new JLabel("init string");
        myDoubleLabel.setBorder(titleDouble);
       
        titleEnum = BorderFactory.createTitledBorder("myEnum");
        myEnumLabel = new JLabel("init string");
        myEnumLabel.setBorder(titleEnum);
       
        GridLayout layout = new GridLayout(3,2,1,1);
        myFrame.setLayout(layout);
       
        myFrame.add(myBoolLabel);
        myFrame.add(myIntLabel);
        myFrame.add(myStringLabel);
        myFrame.add(myDoubleLabel);
        myFrame.add(myEnumLabel);
       
        myFrame.setVisible(true);
        Types types = new Types();
        printTypes(types);
    }
    public static void main(String[] args) {
        new ReflectionTypesTest();
    }
   
    static void printTypes(Types typesObj) {
        Class typesClass = typesObj.getClass();
        Field[] fields = typesClass.getDeclaredFields();
        Class boolClass=null;
        Class intClass=null;
        Class stringClass=null;
        Class doubleClass=null;
        //Class enumClass=null;
       
        for (int i = 0; i < fields.length; i++) {
            String fieldName = fields[i].getName();
            Class typeClass =  fields[i].getType();
            String fieldType = typeClass.getName();
            System.out.println("Name: " + fieldName + ", Type: " + fieldType);
           
            if(typeClass.getName().equals("boolean")) {
                boolClass = fields[i].getType();
            } else if(typeClass.getName().equals("int")) {
                intClass = fields[i].getType();
            } else if(typeClass.getName().equals("java.lang.String")) {
                stringClass = fields[i].getType();
            } else if(typeClass.getName().equals("double")) {
                doubleClass = fields[i].getType();
            }
//            else if(typeClass.getName().equals("enum"))
//            {
//                  fields[i].getType();
//            }
        }
       
        System.out.println("myBool: " + typesObj.getMyBool());
        System.out.println("myString: " + typesObj.getMyString());
        System.out.println("myInt: " + typesObj.getMyInt());
        System.out.println("myDouble: " + typesObj.getMyDouble());
/*
//This is good if I already know the Types to do the Cast
          myBoolLabel.setText(Boolean.toString(typesObj.getMyBool()));
          myIntLabel.setText(Integer.toString(typesObj.getMyInt()));
          myDoubleLabel.setText(Double.toString(typesObj.getMyDouble()));
          //myEnumLabel.setText();//how to handle enums?
          myStringLabel.setText(typesObj.getMyString());//already a String
 */
//ERROR HERE     How to I do it if all I have is the field reference?
        myBoolLabel.setText(boolClass.cast(typesObj.getMyBool()));
        myIntLabel.setText(intClass.cast(typesObj.getMyInt()));
        myDoubleLabel.setText(doubleClass.cast(typesObj.getMyDouble()));
        //myEnumLabel.setText();//how to handle enums?
        myStringLabel.setText(typesObj.getMyString());//already a String
       
    }
   
   
   
}

class Types {
    public boolean myBool = true;
    public int myInt = 5;
    public String myString = "Hello";
    public double myDouble = 10.0;
    //add enum type
    public boolean getMyBool(){return myBool;}
    public int getMyInt(){return myInt;}
    public String getMyString(){return myString;}
    public Double getMyDouble(){return myDouble;}
}
/*
enum myEnum
{
ONE(1),
TWO(2),
THREE(3);
 
myEnum(int val) { value = (byte) val; }
}
 */
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of mitchguy
mitchguy

ASKER

I cannot believe that is all I had to do. I had know idea i could do that.
I spent all this time making the example program to help explain my problem and you answered the first part in 2 seconds
Any insight on how to handle enum types?
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
x might not *be* an Object ;-)

>>Any insight on how to handle enum types?

Should work as well
>>x might not *be* an Object ;-)

But it *is* overridden so it's OK
:-)