Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Dec 2011
    Posts
    67
    Thanks
    20
    Thanked 1 Time in 1 Post

    Question Help with reflection

    Being new at Java programming, please bear with me

    Using reflection, I run into a problem I hope someone can help me with...


    Field f = someClass.getDeclaredField("fieldName");
    f.setaccessible(true);
    Object fieldValue = f.get(someClass);

    This is possible, but what if I don't want to use object but cast the result of f.get to a class... but this class is unknown till runtime; is that possible to do, and how should it be done?

    Class x = anotherClass.newInstance();
    x objectX = (x) f.get(someClass);


    any help?

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    I could probably think of a way to do this, but not like you have it here.
    I don't see a reason to do this at all nonetheless. f.get would be of type object, and this can be cast, but even converting it to a runtime cast doesn't really make any difference since you cannot operate on it. It is nothing more than an Object, and with no known type in this way you wouldn't be able to compile the code if you attempt to operate on it if its a different type.
    Field will have a type associated with it though, so you can pull that off of getType. That can be used in an if/elseif check to determine how to pull the data out or cast as appropriate.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •