Re: Generics
On Mar 6, 8:27 am, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.net> wrote:
Todd wrote:
Hello,
I have been reading about generics to determine if there is a way to
accomplish what I _assumed_ could be done. From what I can tell, what
I would like to do is not possible, but, honestly, generics are
confusing to me.
What I would like to do is have one method, say getValue(), that
returns each member of a mixed collection in its correct type. I have
determined the the object type when storing it into the map, so it is
available to me for use in the getValue() method. I thought that
something along the lines of
public <T> T getValue()
{
return ObjectType.cast( value );
}
would work. However, I am having no luck coming up with anything that
compiles, let alone runs, to return typed objects at runtime using a
single method.
I have searched through the group, but have not found anything that
clarifies for me whether this concept can be implemented.
Is there a way to return typed objects from a mixed collection at
runtime using a single method? If so, could you provide me some tips
as to how to create the method or class with method to do so?
Thanks in advance,
Todd
Generics are determined either by the caller, or by the instantiater,
not by the returner.
Now, if did this:
public <T> T getValueAs(Class<T> type) {
return type.cast(value);
}
you might have better luck.
Or, better off:
class MyRef<T> {
T value;
public MyClass() {
}
public void setValue(T value) {
this.value = value;
}
public T getValue() {
return value;
}
}
MyRef<String> string = new MyRef<String>();
string.setValue("Hello!");
assert string.getValue().equals("Hello!");
What is it exactly that you are trying to do? I mean, what feature are
you adding that needs this?
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
I am reading a data file that contains a mix of doubles, double
arrays, integers, integer arrays, booleans and strings. Each entry
has a name (its key) and value associated with it. I know that when I
request "NumEntries" that the return will be an integer, so I thought
I would code something like
Integer numEntries = getValue( "NumEntries" );
and have an integer return. Further example, knowing "Description"
contains a string I would code something like
String description = getValue( "Description" );