Home > Net >  How to use set() method for T type
How to use set() method for T type

Time:10-08

I work with XML doc. There are a lot of similar tags and methods in my programm. All they do the same things but all they return and have as parameters different objects. Inside this method I check two String. So, can use T instead different objects. All this objects not connected. For example, I want to do the following:

    private <T> T checkBusinessEntityTypeCode(CheckDtKdt checkDtKdt, T kdtCode, T dtCode) {
    if (kdtCode != null && dtCode != null) {
        if (StringUtils.compare(kdtCode..getValue(), dtCode.getValue()) != 0) {
            checkFieldsDtKdtService.save14Graph(checkDtKdt, dtCode.getValue(), kdtCode.getValue());
            dtCode.setValue(kdtCode.getValue());
        }
        if (StringUtils.compare(kdtCode.getCodeListId(), dtCode.getCodeListId()) != 0) {
            checkFieldsDtKdtService.save14Graph(checkDtKdt, dtCode.getCodeListId(), kdtCode.getCodeListId());
            dtCode.setCodeListId(kdtCode.getCodeListId());
        }
    }
}

Of course, this code doesn't work. Because of get() and set() method. Can I use something like that?

CodePudding user response:

You can use the Java Upper Bound Generics for example you can write a super class where you put an inherited or abstract get and set methods :

  private <T extends ApplicationController> T checkBusinessEntityTypeCode(String checkDtKdt, T kdtCode, T dtCode){.... }

ApplicationController is our Superclass (can be an interface) , all "T" classes inherit from it so all references from any T can call the get and set methods .

Just be carefull you need to read more about upper and lower bound generics before using it , using bounds with Collections make the collections immutables with many other tricks ...

Link to Oracle documentation : https://docs.oracle.com/javase/tutorial/java/generics/bounded.html

you can read This answer from StackOverFlow :

Understanding bounded generics in java. What is the point?

  ---------------------------------------------------

Your code compile in my IDE and i can call methods of GvtApplicationController with the reference kdtCode(compile time) :

    private <T extends GvtApplicationController> T checkBusinessEntityTypeCode(String checkDtKdt, T kdtCode, T dtCode) {
    if (kdtCode != null && dtCode != null) {
        kdtCode.getCurrentVersionPath();
    }
    return dtCode;
    }

Example :

abstract class Person{
public abstract String getName();
}
class Student extends Person{
@Override
public String getName() {
    return "MyName";
}
}
class GenericsBounder{
public static<T extends Person> String showName(T t){
    return t.getName();
}
}
public class  Bounder{
public static void main(String[] args) {
String s=   GenericsBounder.showName(new Student());
System.out.println(s);
}
}

Output :

  |MyName
  • Related