java.lang.NoSuchFieldException:java.lang.String - 使用string.class.getDeclaredField(test);

时间:2013-11-21 18:16:35

标签: java string exception

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;
    }
}

1 个答案:

答案 0 :(得分:0)

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;
}