【问题标题】:java.lang.NoSuchFieldException: java.lang.String - Used string.class.getDeclaredField(test);java.lang.NoSuchFieldException: java.lang.String - 使用 string.class.getDeclaredField(test);
【发布时间】:2013-11-21 18:16:34
【问题描述】:
package com.dev.java.string;

import java.lang.reflect.Field;

/**
 * @author ajay
 *
 */
public class TestStringLiteral {

    public static void main(String[] args) {
        TestStringLiteral literal = new TestStringLiteral();
        String abc ="ajay";
        System.out.println(literal.showInternalCharArrayHashCode(abc));
        String bdf = "ajay";
        System.out.println(literal.showInternalCharArrayHashCode(bdf));
    }

    private int showInternalCharArrayHashCode(String test) {
        int value1 = 0;
        try {
            final Field value = String.class.getDeclaredField(test);
            value1 = value.get(test).hashCode();
        } catch (NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return value1;
    }
}

【问题讨论】:

    标签: java string exception


    【解决方案1】:

    take a look here

    试试这个...

     public static void main(String[] args) {
        TestStringLiteral literal = new TestStringLiteral();
        String abc ="ajay";
        System.out.println(literal.showInternalCharArrayHashCode("abc",literal));
        String bdf = "ajay";
        System.out.println(literal.showInternalCharArrayHashCode("bdf", literal));
    }
    
    private int showInternalCharArrayHashCode(String test, Object obj) {
        int value1 = 0;
        try {
            final Field value = getClass().getDeclaredField(test);
            value1 = value.get(obj).hashCode();
        } catch (NoSuchFieldException | SecurityException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return value1;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-14
      • 1970-01-01
      • 2021-09-01
      • 2021-11-25
      • 1970-01-01
      相关资源
      最近更新 更多