dimanche 13 octobre 2019

How can i convert Protocol string to Spymemcached Protocol enum using Java Reflection?

I have a Java 5 application that uses Spymemcached and am having a problem when I want to convert the Protocol string to Enum object. Let's take a look into the following:

  1. The enum Protocol is in ConnectionFactoryBuilder class.
package net.spy.memcached;

...

public class ConnectionFactoryBuilder {

    public enum Protocol {
        TEXT, BINARY

        private Protocol() {
            // compiled code
        }
    }
  1. Now I need to convert string "TEXT" or "BINARY" to the above ConnectionFactoryBuilder.Protocol enum. I tried the following code but nothing works.
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, 

    }

}

Please help, thanks!





Aucun commentaire:

Enregistrer un commentaire