如何在Java中解决java.lang.NullPointerException错误?

huangapple go评论77阅读模式
英文:

How to Solve this java.lang.NullPointerException Error in Java?

问题

I don't know why I am getting the null pointer error.

java.lang.NullPointerException
在 web.index.getMessage(index.java:30) 处
在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) 处
在 java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) 处
在 java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) 处
在 java.base/java.lang.reflect.Method.invoke(Method.java:566) 处
在 javax.el.ELUtil.invokeMethod(ELUtil.java:227) 处
在 javax.el.BeanELResolver.invoke(BeanELResolver.java:440) 处
在 javax.el.CompositeELResolver.invoke(CompositeELResolver.java:198) 处
在 com.sun.el.parser.AstValue.getValue(AstValue.java:110) 处
在 com.sun.el.parser.AstValue.getValue(AstValue.java:177) 处
在 com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:183) 处
在 org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50) 处
在 com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:216) 处
在 com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:123) 处
在 com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:44) 处
在 com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:41) 处
在 com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:169) 处
在 javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650) 处
在 javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650) 处
在 com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468) 处
在 com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170) 处
在 javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132) 处
在 com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102) 处
在 com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76) 处
在 com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199) 处
在 javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708) 处
在 javax.faces.webapp.FacesServlet.service(FacesServlet.java:451) 处
在 org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628) 处
在 org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258) 处
在 org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160) 处
在 org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755) 处
在 org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575) 处
在 com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99) 处
在 org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159) 处
在 org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371) 处
在 org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238) 处
在 com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520) 处
在 com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217) 处
在 org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182) 处
在 org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156) 处
在 org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218) 处
在 org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95) 处
在 org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260) 处
在 org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177) 处
在 org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109) 处
在 org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88) 处
在 org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53) 处
在 org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524) 处
在 org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89) 处
在 org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94) 处
在 org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33) 处
在 org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114) 处
在 org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569) 处
在 org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549) 处
在 java.base/java.lang.Thread.run(Thread.java:834)

在包 web 中的 index.java 文件:

package web;

import ejb.EmployeeFacadeLocal;
import entities.Employee;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;

@Named(value = "index")
@SessionScoped
public class index implements Serializable {

    @EJB
    EmployeeFacadeLocal employee;

    public index() {
    }

    public String getMessage() {
        Employee emp = new Employee(Integer.SIZE, "XYZ");
        System.out.print(emp); /* Printing Objects */
        employee.create(emp);
        return "Hello All";
    }
}

在包 ejb 中的 EmployeeFacade.java 文件:

package ejb;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

public class EmployeeFacade {

    @PersistenceContext(unitName = "TODO-5PU")
    private EntityManager em;

    protected EntityManager getEntityManager() {
        return em;
    }

}

在包 ejb 中的 AbstractFacade.java 文件:

package ejb;

import java.util.List;
import javax.persistence.EntityManager;

public abstract class AbstractFacade<T> {

    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        System.out.print(entity);
        getEntityManager().persist(entity);
    }
}

在包 ejb 中的 EmployeeFacadeLocal.java 文件:

package ejb;

import entities.Employee

<details>
<summary>英文:</summary>

  I dont know why i am getting the null pointer error .

java.lang.NullPointerException
	at web.index.getMessage(index.java:30)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:566)
	at javax.el.ELUtil.invokeMethod(ELUtil.java:227)
	at javax.el.BeanELResolver.invoke(BeanELResolver.java:440)
	at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:198)
	at com.sun.el.parser.AstValue.getValue(AstValue.java:110)
	at com.sun.el.parser.AstValue.getValue(AstValue.java:177)
	at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:183)
	at org.jboss.weld.module.web.el.WeldValueExpression.getValue(WeldValueExpression.java:50)
	at com.sun.faces.facelets.el.ELText$ELTextVariable.writeText(ELText.java:216)
	at com.sun.faces.facelets.el.ELText$ELTextComposite.writeText(ELText.java:123)
	at com.sun.faces.facelets.compiler.TextInstruction.write(TextInstruction.java:44)
	at com.sun.faces.facelets.compiler.UIInstructions.encodeBegin(UIInstructions.java:41)
	at com.sun.faces.facelets.compiler.UILeaf.encodeAll(UILeaf.java:169)
	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
	at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1650)
	at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:468)
	at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:170)
	at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:132)
	at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:102)
	at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:76)
	at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:199)
	at javax.faces.webapp.FacesServlet.executeLifecyle(FacesServlet.java:708)
	at javax.faces.webapp.FacesServlet.service(FacesServlet.java:451)
	at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1628)
	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:258)
	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
	at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:755)
	at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:575)
	at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:159)
	at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:371)
	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:238)
	at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:520)
	at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:217)
	at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
	at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
	at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
	at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
	at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
	at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
	at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:524)
	at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
	at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
	at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
	at java.base/java.lang.Thread.run(Thread.java:834)  
package web;
        
        import ejb.EmployeeFacadeLocal;
        import entities.Employee;
        import javax.inject.Named;
        import javax.enterprise.context.SessionScoped;
        import java.io.Serializable;
        import javax.ejb.EJB;
        
        @Named(value = &quot;index&quot;)
        @SessionScoped
        public class index implements Serializable {
        
        @EJB
        EmployeeFacadeLocal employee;
        public index() {
            } 
            public String getMessage(){
                Employee emp = new Employee(Integer.SIZE,&quot;XYZ&quot;);
                System.out.print(emp) */ Printing Objects */
                employee.create(emp);
                return &quot;Hello All&quot;;
            }
        }
        
           
  

  package ejb;
    
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    
    public class EmployeeFacade {
    
        @PersistenceContext(unitName = &quot;TODO-5PU&quot;)
        private EntityManager em;
    
        @override
        protected EntityManager getEntityManager() {
            return em;
        }
        
    }
    

 package ejb;
    
    import java.util.List;
    import javax.persistence.EntityManager;
    
    
    public abstract class AbstractFacade&lt;T&gt; {
    
        private Class&lt;T&gt; entityClass;
    
        public AbstractFacade(Class&lt;T&gt; entityClass) {
            this.entityClass = entityClass;
        }
    
        protected abstract EntityManager getEntityManager();
    
        public void create(T entity) {
            System.out.print(entity);
            getEntityManager().persist(entity);
        }
    }


    package ejb;
        
        import entities.Employee;
        import java.util.List;
        import javax.ejb.Local;**strong text**
        @Local
        public interface EmployeeFacadeLocal {
        
            void create(Employee employee);
        }
        
  

  package entities;
    
    import java.io.Serializable;
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import javax.validation.constraints.Size;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @Entity
    @Table(name = &quot;employee&quot;)
    @XmlRootElement
    @NamedQueries({
        @NamedQuery(name = &quot;Employee.findAll&quot;, query = &quot;SELECT e FROM Employee e&quot;),
        @NamedQuery(name = &quot;Employee.findById&quot;, query = &quot;SELECT e FROM Employee e WHERE e.id = :id&quot;),
        @NamedQuery(name = &quot;Employee.findByName&quot;, query = &quot;SELECT e FROM Employee e WHERE e.name = :name&quot;)})
    public class Employee implements Serializable {
    
        private static final long serialVersionUID = 1L;
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Basic(optional = false)
        @Column(name = &quot;ID&quot;)
        private Integer id;
        @Size(max = 255)
        @Column(name = &quot;NAME&quot;)
        private String name;
    
        public Employee() {
        }
    
        public Employee(Integer id , String name) {
            this.id = id;
            this.name = name;
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public int hashCode() {
            int hash = 0;
            hash += (id != null ? id.hashCode() : 0);
            return hash;
        }
    
        @Override
        public boolean equals(Object object) {
            // TODO: Warning - this method won&#39;t work in the case the id fields are not set
            if (!(object instanceof Employee)) {
                return false;
            }
            Employee other = (Employee) object;
            if ((this.id == null &amp;&amp; other.id != null) || (this.id != null &amp;&amp; !this.id.equals(other.id))) {
                return false;
            }
            return true;
        }
    
        @Override
        public String toString() {
            return &quot;entities.Employee[ id=&quot; + id + &quot;]&quot;;
        }
        
    }
         


</details>


# 答案1
**得分**: 2

"getMessage"在第30行接收到一个"null"检查这个值来自哪里你应该能够找到问题的原因

<details>
<summary>英文:</summary>

The &quot;getMessage&quot; at line 30 receives a &quot;null&quot; value. Check from where that values comes and you should be able to pinpoint your problem.

</details>



huangapple
  • 本文由 发表于 2020年7月22日 03:45:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/63022010.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定