Skip to main content

How do I give a generic variable a value?

Please note these java.net forums are being decommissioned and use the new and improved forums at https://community.oracle.com/community/java.
1 reply [Last post]
phil1234
Offline
Joined: 2011-07-15

Hi,
assuming I have got the class ExampleClass:
public class ExampleClass() {
public <D> D doSomething(D value) {
D value2;
D = ...;
return D;
}
}
How do I give value2 a value (for example an Integer or a String) because it is not possible to do a simple type convertion (D)"a string"?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
OneJumpedUp
Offline
Joined: 2012-04-05

Hey
You dont give D a value, as such, D is a type see my code below

    public static void main(String[] args) 
    {
        ExampleClass e = new ExampleClass();
        int n = 5;
        char c = 'q';
        int a = e.doSomething( n );
        char f = e.doSomething( c );
       
        DummyClass z = new DummyClass(); // this is the cool stuff
        z.setValue( 10 );
       
        DummyClass x = e.doSomething( z );
       
        System.out.printf( "a = %d\nf = %c\n", a, f );
        System.out.printf( "x = %d\n", x.getValue() );
    }

This is what's called a template function, you you can pass different types including classes

public class ExampleClass 
{
    public <D> D doSomething(D value)
    {
        D value2 = value; // you set value2 to the value (and type) you pass
        return value2;
    }
}
public class DummyClass 
{
    int value;

    public int getValue()
    {
        return value;
    }

    public void setValue(int value)
    {
        this.value = value;
    }
}