How to change the runtime type of a new instance

That's my problem.

public class Row{
  //It is just a class
}

public class RowUsedByThisClass{

  public Row someOp(Row r){
   /*I am Using this method with r a instance of Row.
    *r may be sub type of the Row. I have to inspect r and have to 
    *return a new instance. But the new instance just cant be type
    *Row it should be exact subtype r belongs.In shor i have to 
     *determin the type of return object runtime.
    *Is it possible in java? Can i use generics.
    */
  }

}
+3
source share
7 answers

If you have a no-arg constructor for each subclass Row, then inside someOpyou can use r.getClass().newInstance().

+2
source

This requires reflection, not generics:

Row newRow = r.getClass().newInstance();

However, this requires the class to have a default constructor (no parameters).

+1
source

, someOp() Row.

op .

+1

getClass() .

0
source

In fact, you have 2 ways to determine the type of object.

The instanceof keyword is used first:

if (row instanceof MyRow) {
    // do something
}

The second uses getClass ():

Class clazz = row.getClass();
if (clazz.equals(MyRow.class)) {}
if (MyRow.calss.isAssignableFrom(clazz)) {}

Then you can decide what you want. For example, you can even create a new instance of another class that extends Row and returns it or wraps the string passed using the argument.

0
source

You can and should indicate that in a signature like:

public class RowUsedByThisClass <T extends Row> {
  public T someOp (T t) {
0
source

You can use reflection API and some generics to achieve what you want.

import java.lang.reflect.Constructor;

class Row {
    //It is just a class
}

class RowUsedByThisClass {

    public <R extends Row> R someOp(final R r) {
        R newR = null;
        try {
            // Use no-args constructor
            newR = (R) r.getClass().newInstance();
            // Or you can use some specific constructor, e.g. in this case that accepts an Integer, String argument
            Constructor c = r.getClass().getConstructor(Integer.class, String.class);
            newR = (R) c.newInstance(1, "2");

            // do whatever else you want
        } catch (final Exception ex) {
            // TODO Handle this: Error in initializing/cconstructor not visible/...
        }
        return newR;
    }
}
0
source

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


All Articles