C # in Java: where T: new () Syntax

I am porting code in C # to Java. I am having problems with the syntax, namely with the new (). I understand where similar to Java generic: T extends FOO.

How can I replicate a new argument () in Java?

"The new () Constraint lets the compiler know that any type argument should be accessible without parameters - or the default constructor." - MSDN

t

public class BAR<T> : BAR
       where T : FOO, new()

Here's how I implemented the cletus solution:

public class BAR<T extends FOO> extends ABSTRACTBAR {
    public BAR(T t) throws InstantiationException, IllegalAccessException{ 
        t.getClass().newInstance();
        this.value = t;
    }
}
+3
source share
3 answers

Java, # Java. Java , ( ) . generic type, :

public class Bar<T extends Foo> {
  private final Class<T> clazz;

  public class Bar(Class<T> clazz) {
    this.clazz = clazz;
  }

  public T newInstance() {
    return clazz.newInstance(); // this will throw checked exceptions
  }
}

: , : , Java - : . . Collections.checkedList():

List<String> list = Collections.checkedList(new ArrayList<String>(),
                      String.class);

, -, String.

+7

. Java generic , , .

0

Hope this helps. Note that this requires the no-arg constructor, which creates a new instance.


public class TypeStuff {

    private static final long serialVersionUID = 1L;

    // *** PUBLIC STATIC VOID MAIN ***
    public static void main(String[] args) {
        TypeStuff ts = new TypeStuff();
        ts.run();
    }

    // *** CONSTRUCTOR ***
    public TypeStuff () {
    }

    public void run() {
        Fruit banana = new Banana();

        Fruit dupe = newT(banana);
        System.out.println("dupe.getColor()=" + dupe.getColor());

        Fruit orange = new Orange();
        Fruit dupe2 = newT(orange);
        System.out.println("dupe2.getColor()=" + dupe2.getColor());
    }

    public <T extends Fruit> T newT(T fruit) {
        T dupe = null;
        try {
            Class clazz = fruit.getClass();
            dupe = (T) clazz.newInstance();
        } catch (Exception ex) {
        } finally {
            return dupe;
        }
    }

    interface Fruit {
        String getColor();
    }
    static class Banana implements Fruit {
        public Banana() {
        }
        @Override
        public String getColor() {
            return "Yellow";
        }
    }
    static class Orange implements Fruit {
        public Orange() {
        }
        @Override
        public String getColor() {
            return "Orange";
        }
    }


} // CLOSE CLASS.


0
source

Source: https://habr.com/ru/post/1740717/


All Articles