如何使用Java Reflection将协议字符串转换为Spymemcached协议枚举?

时间:2019-10-13 17:11:31

标签: java reflection enums

我有一个使用Spymemcached的Java 5应用程序,当我想将Protocol字符串转换为Enum对象时遇到问题。让我们看一下以下内容:

  1. 枚举协议位于ConnectionFactoryBuilder类中。
package net.spy.memcached;

...

public class ConnectionFactoryBuilder {

    public enum Protocol {
        TEXT, BINARY

        private Protocol() {
            // compiled code
        }
    }
  1. 现在,我需要将字符串“ TEXT”或“ BINARY”转换为上述ConnectionFactoryBuilder.Protocol枚举。我尝试了以下代码,但无济于事。
package mypackage;

import java.lang.reflect.Field;

public class Test {

    public static void main(String[] args) throws Exception {

        String protocolString = "TEXT";

        // code 1:
        String protocolClassName1 = "net.spy.memcached.ConnectionFactoryBuilder.Protocol";
        Class protocolType1 = Class.forName(protocolClassName1); 
        // The above line throws: Exception in thread "main" java.lang.ClassNotFoundException: net.spy.memcached.ConnectionFactoryBuilder.Protocol
        Object protocolEnumObject1 = Enum.valueOf(protocolType1, protocolString);


        // code 2:
        Class connectionFactoryBuilderClass2 = Class.forName("net.spy.memcached.ConnectionFactoryBuilder");
        Field protocolField2 = null;
        for (Field f : connectionFactoryBuilderClass2.getDeclaredFields()) {
            System.out.print(f.getName() + ", ");
            if (f.getName().equalsIgnoreCase("Protocol")) {
                protocolField2 = f;
            }
        }
        Class protocolType2 = protocolField2.getType();
        Object protocolEnumObject2 = Enum.valueOf(protocolType2, protocolString);
        // In this approach, i can not get protocol field in that ConnectionFactoryBuilder class, here are output of getDeclaredFields():
        // opQueueFactory, readQueueFactory, writeQueueFactory, transcoder, failureMode, 
        // initialObservers, opFact, locator, opTimeout, isDaemon, shouldOptimize, useNagle, 
        // maxReconnectDelay, readBufSize, hashAlg, authDescriptor, opQueueMaxBlockTime, 
        // timeoutExceptionThreshold, metricType, collector, executorService, authWaitTime, $assertionsDisabled, 

    }

}

请帮助,谢谢!

1 个答案:

答案 0 :(得分:0)

好的,我已经找到解决方法。基本上,枚举协议是ConnectionFactoryBuilder中的嵌套类,因此我需要使用$来定位它。

这里是已解决的代码:

package mypackage;

public class Test {

    public static void main(String[] args) throws Exception {

        String protocolString = "TEXT";

        // code 1:
        // OLD: String protocolClassName1 = "net.spy.memcached.ConnectionFactoryBuilder.Protocol";
        String protocolClassName1 = "net.spy.memcached.ConnectionFactoryBuilder$Protocol";
        Class protocolType1 = Class.forName(protocolClassName1); 
        Object protocolEnumObject1 = Enum.valueOf(protocolType1, protocolString);

        System.out.println(protocolEnumObject1.getClass());
        // class net.spy.memcached.ConnectionFactoryBuilder$Protocol

    }

}