接收Object的方法将其转换为现有的pojo

问题描述

所以,我有这样的pojo:

public class pojo {
   String name;
   String address;
   String email;

   // getter's and setter's here...
}

使用一种接收类型对象的方法,如何将其转换为原始类型,以便可以使用所有getter和setter。

private void method(Object obj) {
   // use get's and set's from the original object of type "pojo"
   // instead of the methods from java.lang.Object
}

我真的不知道如何更好地解释它,这让我有些困惑。希望大家都明白。 预先感谢

编辑1
所以,我并没有很好地解释它,因为我有些困惑,我什至不知道我想做的事是否可行。但是,在方法内部,我想以某种方式执行以下操作:

public void method(Object obj) {

   **Dynamically detect obj type** newObj = (obj type) obj;

   // I want to do like this,because this method will never kNow what 
   // object type I am passing.
   // I will have more than 10 pojo's and I wanted the method to detect
   // and create them dynamically.
}

解决方法

您可以使用投射

这里我们在一个空的构造函数中创建一个Pojo对象,然后将其作为对象发送给方法

static void unionLength(int a[][],int sets)
{
    TreeMap<Integer,Boolean> t=new TreeMap<>();
    
    
    for(int i=0;i<sets;i++)
    {
         t.put(a[i][0],false);
         t.put(a[i][1],true);
         
         
    }
int count=0;
int res=0;
int one=1;
Set set = t.entrySet();
Iterator it = set.iterator();

int prev=0;

while(it.hasNext()) {
    if(one==1){
          Map.Entry me = (Map.Entry)it.next();
          one=0;
          prev=(int)me.getKey();
          if((boolean)me.getValue()==false)
              count++;
          else
              count--;
    }
    
  Map.Entry me = (Map.Entry)it.next();

  if(count>0)
      res=res+((int)me.getKey()-prev);
  
  if((boolean)me.getValue()==false)
      count++;
  else
      count--;

   prev=(int)me.getKey();

} 
System.out.println(res);
}
 public static void main(String []args){
    
    int a[][]={{0,4},{3,6},{8,10}};
    int b[][]={{5,10},12}};
    unionLength(a,3);
    unionLength(b,2);
       
 }

我们的方法将obj(这是一个普通的java对象)并将其作为Pojo对象转换为已经是Pojo对象的测试(我们这样做是为了可以使用Pojo类的方法)。 然后我们将其设置为名称。

public static void main(String[] args) {
        
        Pojo pojo=new Pojo();
        pojo.method(pojo);
        System.out.println(pojo.getName());

    }
,

您必须使用强制转换。

let dJson ='{JSON}'


// GET ALL SENDER OR RECEIVERS NAME AS KEY

let allNames = [] // all mail names,includes dublicate

const p_me = JSON.parse(dJson);

p_me['lol'].forEach(item => {
  if (item.receiverInfo.name.toLowerCase() !== "me") {
    allNames.push(item.receiverInfo.name.toLowerCase())
  } else {
    allNames.push(item.senderInfo.name.toLowerCase())
  }
})




// REMOVE Dublicates Using Set Object 


let names = [...new Set(allNames)];


// Get The New Filtered List 
let MyList = [] // The required list

for (name of names) {
  for (obj of p_me['lol']) {

    if (obj.receiverInfo.name.toLowerCase() == name || obj.senderInfo.name.toLowerCase() == name) {

      //Get the first match and disregard the rest for the same name
      MyList.push(obj)
      break
    }
  }

}

编辑:或者您可以使用Java reflection API to get the name of the class,然后使用适当的转换。

要获取类的名称,请使用以下命令: private void method(Object obj) { Pojo p = (Pojo) obj; //Now you can use the pojo methods. p.getName(); //And other methods depending on what methods you have defined in Pojo }

然后,您可以使用开关盒来使用适当的铸件。

,

在投射前用instanceof测试。

Pojo pojo = Pojo的obj实例? (Pojo)pojo:新的Pojo();

,

尝试com.fasterxml.jackson.databind.ObjectMapper

Pojo pojo = new ObjectMapper().readValue(object,Pojo.class)

这会将您的对象转换为pojo类型,因此可以访问Pojo中的所有方法。

,

您可以简单地使用instanceof运算符进行检查以检测对象的类型。

如果您打算动态创建对象,请进行反思以创建对象。

public void method(Object obj) throws Exception {

    Class<?> clz = obj.getClass();
    Object newObj = clz.newInstance();

    **Dynamically detect obj type** newObj = (obj type) obj;

    // I want to do like this,because this method will never know what 
    // object type I am passing.
    // I will have more than 10 pojo's and I wanted the method to detect
    // and create them dynamically.
}

由于方法返回类型为空,因此必须在该方法内执行业务逻辑,根据不同的对象类型,您需要应用业务逻辑。然后显式检查对象类型以在if块内执行任务。