在外部类java中使用内部类对象 [英] using inner class object in outer class java

查看:218
本文介绍了在外部类java中使用内部类对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将json对象转换为POJO类时遇到问题。

I am facing a problem converting json object to POJO class.

我有一个名为Service的公共类,它有一个内部类User。我想使用内部类作为容器/对象来保存所有外部类方法的变量。我正在尝试执行以下操作,但我收到编译错误。请说明我如何做到这一点,请在下面的代码中纠正我正在做的错误。

I have a public class called Service and it has an inner class User. I want to use the inner class as a container/object to hold the variables for all my outer class methods. I am trying to do the below, but I am getting compilation errors. Please show how I can do this and please correct the mistake I am doing in my code below.

从eclipse调试窗口,我看到下面的json是在节点变量
node中获得的:{firstName:ndndbs,lastName: dnjdnjs}

From eclipse debug window, i see the below json being obtained in node variable node : {"firstName":"ndndbs","lastName":"dnjdnjs"}

试用1:

public class Service {
                             // Method
public boolean createUserAccount(JsonNode node) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
         User user=null;
        try {
            Service service=new Service();
            user = mapper.readValue(node, User.class);    
        } catch (Exception e) {throw new Exception("failed to bind json", e);}

     System.out.println("Use this anywhere in method"+userNode.firstName); 
    }

}
                               // Inner class
public class User {
        public String firstName;
        public String lastName;
    }
        }

OUTPUT:
NULL POINTER EXCEPTION AND user=null even after execution of mapper.readValue() statement


推荐答案

从声明中

user = mapper.readValue(node, User.class);  

不确定NullPointerException的原因(完整的堆栈跟踪可能有帮助)。似乎ObjectMapper试图通过Reflection创建内部类的实例。但是创建内部类和嵌套类的实例并不是直截了当请参阅
是否可以使用Java Reflection创建嵌套类的实例?

Not sure about cause for NullPointerException (a full stacktrace might help ). It appears ObjectMapper is trying to create instance of inner class via Reflection. But creating instance of inner and nested classes is not straight forward See Is it possible to create an instance of nested class using Java Reflection? .

在你的情况下

Service.User.class.class.getConstructors()[0].newInstance(serviceInstance);

而不是

User.class.newInstance() 

这可能属于Usual /外课。我不确定 ObjectMapper 是否能够以这种方式实例化类。

which would have been a case with Usual/Outer classes. I am not sure if ObjectMapper is equipped to instantiate class this way.

我建议移动用户到自己的源User.java中的顶级公共类,除非你有一个我很想知道的特定设计限制。

I suggest moving the User to a top level public class in its own source User.java unless you have a specific design restriction which I am curious to know.

这篇关于在外部类java中使用内部类对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆