1 // Protocol Buffers - Google's data interchange format 2 // Copyright 2008 Google Inc. All rights reserved. 3 // 4 // Use of this source code is governed by a BSD-style 5 // license that can be found in the LICENSE file or at 6 // https://developers.google.com/open-source/licenses/bsd 7 8 package com.google.protobuf; 9 10 import static com.google.protobuf.ExtensionRegistryLite.EMPTY_REGISTRY_LITE; 11 12 /** 13 * A factory object to create instances of {@link ExtensionRegistryLite}. 14 * 15 * <p>This factory detects (via reflection) if the full (non-Lite) protocol buffer libraries are 16 * available, and if so, the instances returned are actually {@link ExtensionRegistry}. 17 */ 18 final class ExtensionRegistryFactory { 19 20 static final String FULL_REGISTRY_CLASS_NAME = "com.google.protobuf.ExtensionRegistry"; 21 22 /* Visible for Testing 23 @Nullable */ 24 static final Class<?> EXTENSION_REGISTRY_CLASS = reflectExtensionRegistry(); 25 reflectExtensionRegistry()26 static Class<?> reflectExtensionRegistry() { 27 try { 28 return Class.forName(FULL_REGISTRY_CLASS_NAME); 29 } catch (ClassNotFoundException e) { 30 // The exception allocation is potentially expensive on Android (where it can be triggered 31 // many times at start up). Is there a way to ameliorate this? 32 return null; 33 } 34 } 35 36 /** Construct a new, empty instance. */ create()37 public static ExtensionRegistryLite create() { 38 ExtensionRegistryLite result = invokeSubclassFactory("newInstance"); 39 40 return result != null ? result : new ExtensionRegistryLite(); 41 } 42 43 /** Get the unmodifiable singleton empty instance. */ createEmpty()44 public static ExtensionRegistryLite createEmpty() { 45 ExtensionRegistryLite result = invokeSubclassFactory("getEmptyRegistry"); 46 47 return result != null ? result : EMPTY_REGISTRY_LITE; 48 } 49 isFullRegistry(ExtensionRegistryLite registry)50 static boolean isFullRegistry(ExtensionRegistryLite registry) { 51 return !Protobuf.assumeLiteRuntime 52 && EXTENSION_REGISTRY_CLASS != null 53 && EXTENSION_REGISTRY_CLASS.isAssignableFrom(registry.getClass()); 54 } 55 invokeSubclassFactory(String methodName)56 private static final ExtensionRegistryLite invokeSubclassFactory(String methodName) { 57 if (EXTENSION_REGISTRY_CLASS == null) { 58 return null; 59 } 60 61 try { 62 return (ExtensionRegistryLite) 63 EXTENSION_REGISTRY_CLASS.getDeclaredMethod(methodName).invoke(null); 64 } catch (Exception e) { 65 return null; 66 } 67 } 68 } 69