Results 1 to 20 of 20
  1. #1
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default [SOLVED] Class question

    Some of you might consider this a quite 'stupid' question, but since I'm not sure and couldn't find any useful hits on Google, I decided to ask it here.

    Is it possible for a method to return a variable Class?

    For example:
    Java Code:
    public Object getIt(Object o) {
        return o;
    }
    
    public static void main(String[] args) {
        String s = "Hello";
        s = getIt(s);
        Integer i = 5;
        i = getIt(i);
    }
    Here I want 'getIt(s)' to return a variable of type String and 'getIt(i)' to return a variable of type Integer.

    Is this possible, or will I need a different method (that does the same) for each 'new' class that'll use the method?

    Btw: no conversions, because I want it to work for arrays too. So no 'just use (String)getIt(s)' please.

    Thx,

    Matt
    Last edited by Supamagier; 05-12-2009 at 10:38 AM. Reason: Solved.
    I die a little on the inside...
    Every time I get shot.

  2. #2
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    getClass() method. Most all java types have that method. and it returns
    "the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class. "
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  3. #3
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    Yes, but
    Java Code:
    public Object getIt(Object o) {
        return o;
    }
    getClass would give me the type of the class, though, the method will still return an Object: 'public Object getIt'
    I need the Object (bold) to be variable.

    Do you see what I mean?
    I die a little on the inside...
    Every time I get shot.

  4. #4
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    ahh ya I see what you mean now but I don't see why this wouldn't work. In your example
    s.getClass() returns String
    i.getClass() returns Integer
    o.getClass() returns Object

    ...."'getIt(s)' to return a variable of type String" meaning it would return new String? Why not just getIt(s) and have it return new (s.getClass())Object

    That way your method will work for any object you send it. You're just type casting the return type to the Object type you want. Does that help or am I still missing what you're trying to do?
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  5. #5
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    Kinda, yes. But what if s happens to be a String array, and I want it to return a String array (String[]) using the same method, but like this:
    Java Code:
    public Object[] getIt(Object[] o) {
        return o;
    }
    As far as I know, you can't convert an Object array to a String array.

    I get this error:
    found : java.lang.Object[]
    required: java.lang.Integer[]
    using this test code
    Java Code:
    Integer[] ia = new Integer[]{1,2,3,4,5,6,7,8,9,0};
    ia = test(ia);
    
    public static Object[] test(Object[] test) {
            Object tr = test[0].newInstance()[10];
            //Object[] tr = new (test[0].getClass())[test.length];
            for (int i = 0; i < 10; ++i)
                tr[i] = test[i];
            return tr;
        }
    Must be doing something wrong.
    I die a little on the inside...
    Every time I get shot.

  6. #6
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    This is getting a little past my readily available knowledge. Perhaps we can get one of the more experienced members to jump in. The only idea that comes to mind is just dropping anything that is an Array and converting it to an ArrayList. However in order to test that I'm picturing a large case statement that determines the return type and object based on test.getClass().

    Do generics work in method headers? Could you have something like
    public static <?> test(){
    return <?>tr;
    }
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  7. #7
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    also I don't get any errors on compile when trying to run
    Java Code:
    	public static Object[] test(Object[] test) {
    	        //Object[] tr = test[0].getClass()[10];
    	        //Object[] tr = new (test[0].getClass())[test.length];
    	        //for (int i = 0; i < 10; ++i)
    	         //   tr[i] = test[i];
    	        return null;
    	}
    	
    	public static Object test(Object test){
    		Object tr = test.getClass();
    		return tr;
    	}
    so it seems you can just use( ....polymorphism?...abstraction?....method overwriting? ya that seems right) to distinguish between arrays and single instance objects.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  8. #8
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    I see what you mean, partly. For single objects it's all fine, because I can just cast the Object to the desired class.

    (Btw, I'm not asking for one method that can both return arrays as single objects, i'm looking for an object that can return an array of any type, without using the superclass Object)

    It seems that there's a tiny misunderstanding here - to make myself clear I'll explain why I want to do this.

    I have this method:
    Java Code:
    String[] appendToArray(final String[] s, final String toAdd) {
            final String[] newString = new String[s.length+1];
            System.arraycopy(s,0,newString,0,s.length);
            newString[s.length] = toAdd;
            return newString;
        }
    And I want this method also for Integers and some other objects. However, I rather don't copy this method like 5 times just to change the return type.

    I don't want to return a general Object array, because I can't use that array unless I create a loop that changes everything - I don't want that.

    Also, please don't tell me to use ArrayLists or something, I have my reasons to use arrays instead.

    Hope this clears things up.
    I die a little on the inside...
    Every time I get shot.

  9. #9
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    7

    Default

    lol I was going to say use ArrayList until I saw that you don't want it. All I can think of is returning an Object[] and then typecasting your object when this method is called. That way you can use generics and the .getClass within your appendToArray method.

    Is there some reason you can't have 5 similar methods?(size constrictions, etc). Because Polymorphism(I know that can't be the right word but I can't think of anything else) is a fundamental part of OOP so why not use it?
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  10. #10
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    It is the right word. :P

    No, no size restrictions or such, but I just find it ugly to have the 'same' method like 5 times.

    Btw, polymorphism isn't of any interest here (I think) because I just want to have one general class that contains useful methods like this. Next to that, it's not just one method i'll have to copy 5 times, it are several.

    Why no conversions like you suggested? Simply saving speed and increase the readability.

    If it's possible, I'm sure someone on this forum knows how to.

    Thanks for your help :)

    ~Matt
    I die a little on the inside...
    Every time I get shot.

  11. #11
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    I don't see any point to the method you are trying to write. It's just a type-cast. If you want a method use Class.cast(). You can do deep casting on arrays after checking with Class.isArray(). If you want to avoid excessive casting, use generics in your code.

    Java Code:
    public <T> T[] appendToArray(T[] array, T object) {
        T[] newArray = (T[])Array.newInstance(object.getClass(), new int[] {array.length + 1});
        for (int i=0; i<array.length; i++) {
            newArray[i] = array[i];
        }
        newArray[array.length] = object;
        return newArray;
    }
    If you want to handle primitive types then yes, you have to implement the same method multiple times, just like in java.util.Arrays.
    Last edited by OrangeDog; 05-11-2009 at 10:19 PM.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  12. #12
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    I think that is what I mean, but I get the following error:
    Test.java:15:30: cannot find symbol
    symbol : class T
    location: class Test
    public T[] appendToArray(T[] array, T object) {
    I die a little on the inside...
    Every time I get shot.

  13. #13
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    Here's a version that should take care of subclasses
    Java Code:
    public <T, S extends T> T[] appendToArray(T[] array, S object) {
        T[] newArray = (T[])Array.newInstance(array.getClass().getComponentType(), new int[] {array.length + 1});
        ... etc
    }
    Last edited by OrangeDog; 05-11-2009 at 10:31 PM.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  14. #14
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    Quote Originally Posted by Supamagier View Post
    I think that is what I mean, but I get the following error:
    Check with the updated code, I forgot the actual parameter first time round.

    Consider whether you actually need to be doing this. Some kind of Collection might be what you are after.
    Last edited by OrangeDog; 05-11-2009 at 10:34 PM.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  15. #15
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    Thanks. :)

    Can you explain what the T and such is and what you're actually doing? I don't like using code I don't understand, you see? ;)
    I die a little on the inside...
    Every time I get shot.

  16. #16
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    This is called Generics and is similar in purpose and syntax (though completely different implementation) to templates in C++. I've also used a bit of Reflection to allocate the new array.

    Lesson: Generics (The Java™ Tutorials > Bonus)
    Trail: The Reflection API (The Java™ Tutorials)

    In short, the code doesn't know what the types will be when it is executed, so we'll call it "T" until it does.
    Last edited by OrangeDog; 05-11-2009 at 11:53 PM.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  17. #17
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    Thanks a lot! :D
    I die a little on the inside...
    Every time I get shot.

  18. #18
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    Btw, I still get this warning:
    Misc.java:97:46: warning: [unchecked] unchecked cast
    found : java.lang.Object
    required: T[]
    T[] newArray = (T[])Array.newInstance(array.getClass().getComponentTy pe(), new int[] {array.length + 1});
    Something bad?
    I die a little on the inside...
    Every time I get shot.

  19. #19
    OrangeDog's Avatar
    OrangeDog is offline Senior Member
    Join Date
    Jan 2009
    Location
    Cambridge, UK
    Posts
    838
    Rep Power
    6

    Default

    Yeah, you can't get rid of that. Generics with arrays is always a bit of a hack (even java.lang.util has unchecked casts). Slap a @SuppressWarnings{"unchecked"} on it and it should be fine.
    Don't forget to mark threads as [SOLVED] and give reps to helpful posts.
    How To Ask Questions The Smart Way

  20. #20
    Supamagier is offline Senior Member
    Join Date
    Aug 2008
    Posts
    384
    Rep Power
    7

    Default

    You probably mean @SuppressWarnings("unchecked") but hey, it works ;)

    Thanks a lot. :)
    I die a little on the inside...
    Every time I get shot.

Similar Threads

  1. Abstract class question
    By McChill in forum New To Java
    Replies: 4
    Last Post: 02-27-2009, 07:52 AM
  2. I have some question about jar and class??
    By low224 in forum New To Java
    Replies: 2
    Last Post: 01-01-2009, 05:02 AM
  3. Abstract Class question
    By maa11235 in forum New To Java
    Replies: 1
    Last Post: 01-05-2008, 11:30 PM
  4. class organization question
    By maa11235 in forum New To Java
    Replies: 0
    Last Post: 12-17-2007, 04:25 AM
  5. question regarding class
    By kavithas in forum New To Java
    Replies: 4
    Last Post: 11-16-2007, 10:12 AM

Posting Permissions

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