简体   繁体   English

使用this.getClass()。getDeclaredField方法时发生NullPointerException

[英]NullPointerException while using this.getClass().getDeclaredField method

I wanted to get only one field name of a POJO, my java POJO look like: 我只想获取一个POJO的字段名称,我的Java POJO如下所示:

public class A1 {

        private String field2;
    private String field1;
    public String getField2() {
        return field2;
    }
    public void setField2(String field2) {
        this.field2 = field2;
    }
    public String getField1() {
        return field1;
    }
    public void setField1(String field1) {
        this.field1 = field1;
    }
    @Override
    public String toString() {
        return "A1 [field2=" + field2 + ", field1=" + field1 + "]";
    }

        public String getFiled1Name() throws NoSuchFieldException, SecurityException{
            return this.getClass().getDeclaredField(field1).getName();
        }

    }

In the client code: 在客户端代码中:

System.out.println(new A1().getFiled1Name());

I am getting NullPointerException 我收到NullPointerException

I tried method this.getClass().getDeclaredFields() and this works as expected. 我尝试了方法this.getClass().getDeclaredFields() ,这按预期工作。 But the problem with this is: It returns all the fields( java.lang.reflect.Field ) and I need to iterate, compare and then return the correct filed name. 但这是一个问题:它返回所有字段( java.lang.reflect.Field ),我需要进行迭代,比较然后返回正确的文件名。

Rather I want to get only one field name and with no hard coded field name in the method. 而是我只想获得一个字段名,并且在该方法中没有硬编码的字段名。 How I can get this? 我怎么能得到这个?

You should supply name of the field instead of field itself as field1 is String which is null and you are passing null to the getDeclaredField , 你应该领域,而不是场本身提供名称field1为字符串,它是null和要传递nullgetDeclaredField

public String getFiled1Name() throws NoSuchFieldException, SecurityException {
    return getClass().getDeclaredField("field1").getName();
}

Class#getDeclareField throws NullPointerException - if name is null Class#getDeclareField抛出NullPointerException如果名称为null


I don't want to hard code "field1" 我不想硬编码“ field1”

You can create a constant for the field name instead of using reflection but for every change in name you also need to update constant. 您可以为字段名称创建一个常量,而不是使用反射,但是对于名称的每次更改,您还需要更新常量。

In other way out you can get all declared fields and access the name of the field from the array. 换句话说,您可以获取所有声明的字段并从数组访问字段的名称。 But be careful while using this as change in the declaration may change behavior of the method. 但是在使用它时要小心,因为声明中的更改可能会更改方法的行为。

public String getFiled1Name() throws NoSuchFieldException, SecurityException {
    return getClass().getDeclaredFields()[0].getName();
}

you need to pass field name as String. 您需要将字段名称传递为String。

 public String getFiled1Name() throws NoSuchFieldException, SecurityException{
    return this.getClass().getDeclaredField("field1").getName();
}

Your field field1 is null. 您的字段field1为空。 You haven't initialized the String. 您尚未初始化字符串。 So that causes the NullPointerException. 因此,将导致NullPointerException。 You're currently just passing null to the getDeclaredField() method. 当前,您只是将null传递给getDeclaredField()方法。

I thought of this, not sure if Thread.currentThread().getStackTrace() is relaiable enugh, however you want something totally dynamic , no hardcoded... so this is my shoot: 我想到了这个,不确定Thread.currentThread().getStackTrace()是否可靠,但是您想要完全动态的东西,没有硬编码...所以这是我的摄影:

public class Reflections {

    private String field2;
    private String field1;

    public static void main(String[] args) {
        Reflections r = new Reflections();
        System.out.println(r.getField1Name());
    }

    private Field fields[] = null;

    public Reflections() {
        fields = getClass().getDeclaredFields();
    }

    public String getField1Name() {

        if(fields == null || fields.length==0){
            return null;
        }

        final StackTraceElement[] stes = Thread.currentThread().getStackTrace();
        if(stes == null || stes.length<2){
            return null;
        }

        final String thisMethodName = stes[1].getMethodName(); // [1] this is supposed to have the name of current method

        for (Field f : fields) {
            if (thisMethodName.toLowerCase().contains(f.getName().toLowerCase())) {
                //System.out.println(f.getName());
                return f.getName();
            }// match
        }// for fields
        return null;
    }// getFiled1Name   
}

in short, getField1Name() tries to find it's own name, and then iterates through fields list of current class, and tries to find a field that it's name is part of the method name. 简而言之, getField1Name()尝试找到其自己的名称,然后遍历当前类的字段列表,并尝试查找其名称属于方法名称的字段。

this could return invalid result sometimes, as some field names might be a sub-part of longer name, and some other cases where the result will not be accurate 有时这可能返回无效的结果,因为某些字段名称可能是较长名称的一部分,而在另一些情况下结果将不准确

but however, here it is, maybe it's useful for you or anyone else. 但是,这可能对您或其他任何人有用。

you can refactor the code, creating new method getFieldNameUsingMethodName() ?? 您可以重构代码,创建新方法getFieldNameUsingMethodName() maybe ?!?! 也许 ?!?! this will do the loop and match thing, in case you have like 10 or more getFieldXname() so you can do it if you think this sol worthy. 如果您有10个或更多的getFieldXname() ,则这将完成循环并进行匹配操作,因此,如果您认为此溶胶值得,则可以执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 带有this.getClass()。newInstance()的通用main方法 - Universal main method with this.getClass().newInstance() this.getClass()。getClassLoader()和ClassLoader - this.getClass().getClassLoader() and ClassLoader this.getClass()。getResource()。openStream(“file.xls”)返回NullPointerException(MAVEN项目) - this.getClass().getResource().openStream(“file.xls”) returns NullPointerException (MAVEN project) “ this.getClass()。getSuperclass()”的意外输出 - Unexpected output of “this.getClass().getSuperclass()” this.getClass()。getClassLoader()。getResource()==异常 - this.getClass().getClassLoader().getResource() == Exception 为什么在Java中这是可能的:this.getClass()。getClass()。getClass()...等 - Why is this possible in Java: this.getClass().getClass().getClass()…etc 如何使用this.getClass()。getResource(String)? - How to use this.getClass().getResource(String)? 是否可以在调用super()之前访问this.getClass() - Is it possible to acces this.getClass() before calling super() Openshift this.getClass()。getResource()路径可能不正确 - Openshift this.getClass().getResource() path probably not correct 如何获得超类的this.getClass()。getConstructor? - How to get this.getClass().getConstructor of a super class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM