@Test public void returnIOSGDXFacebookWhenOnIOS() { Application mockApplication = mock(Application.class); when(mockApplication.getType()).thenReturn(Application.ApplicationType.iOS); Gdx.app = mockApplication; try { Constructor mockConstructor = PowerMockito.mock(Constructor.class); GDXFacebook mockFacebook = mock(IOSGDXFacebook.class); when(ClassReflection.forName(GDXFacebookVars.CLASSNAME_IOS)).thenReturn(IOSGDXFacebook.class); when(ClassReflection.getConstructor(IOSGDXFacebook.class, GDXFacebookConfig.class)).thenReturn(mockConstructor); when(mockConstructor.newInstance(anyObject())).thenReturn(mockFacebook); } catch (ReflectionException e) { e.printStackTrace(); } facebook = GDXFacebookSystem.install(new GDXFacebookConfig()); assertTrue(facebook instanceof IOSGDXFacebook); }
@Test public void returnDesktopGDXFacebookWhenOnDesktop() { Application mockApplication = mock(Application.class); when(mockApplication.getType()).thenReturn(Application.ApplicationType.Desktop); Gdx.app = mockApplication; try { Constructor mockConstructor = PowerMockito.mock(Constructor.class); GDXFacebook mockFacebook = mock(DesktopGDXFacebook.class); when(ClassReflection.forName(GDXFacebookVars.CLASSNAME_DESKTOP)).thenReturn(DesktopGDXFacebook.class); when(ClassReflection.getConstructor(DesktopGDXFacebook.class, GDXFacebookConfig.class)).thenReturn(mockConstructor); when(mockConstructor.newInstance(anyObject())).thenReturn(mockFacebook); } catch (ReflectionException e) { e.printStackTrace(); } facebook = GDXFacebookSystem.install(new GDXFacebookConfig()); assertTrue(facebook instanceof DesktopGDXFacebook); }
@Test public void returnHTMLGDXFacebookWhenOnWebGL() { Application mockApplication = mock(Application.class); when(mockApplication.getType()).thenReturn(Application.ApplicationType.WebGL); Gdx.app = mockApplication; try { Constructor mockConstructor = PowerMockito.mock(Constructor.class); GDXFacebook mockFacebook = mock(HTMLGDXFacebook.class); when(ClassReflection.forName(GDXFacebookVars.CLASSNAME_HTML)).thenReturn(HTMLGDXFacebook.class); when(ClassReflection.getConstructor(HTMLGDXFacebook.class, GDXFacebookConfig.class)).thenReturn(mockConstructor); when(mockConstructor.newInstance(anyObject())).thenReturn(mockFacebook); } catch (ReflectionException e) { e.printStackTrace(); } facebook = GDXFacebookSystem.install(new GDXFacebookConfig()); assertTrue(facebook instanceof HTMLGDXFacebook); }
/** @param types classes of components to initiate. * @param context will contain components mapped by their classes tree. * @return an array containing all created components. */ private Array<Object> createComponents(final Array<Class<?>> types, final Context context) { final Array<Object> components = GdxArrays.newArray(); for (final Class<?> type : types) { final Constructor[] constructors = ClassReflection.getConstructors(type); if (constructors == null || constructors.length == 0) { throw new ContextInitiationException( type + " has no available public constructors. Unable to create component."); } else if (constructors.length == 1) { // Single constructor - trying to invoke it: addIfNotNull(components, processConstructor(constructors[0], context)); } else { // Multiple constructors - trying to find a suitable one: addIfNotNull(components, processConstructor(findSuitableConstructor(constructors), context)); } } int initiationIterations = 0; while (GdxArrays.isNotEmpty(delayedConstructions)) { validateIterationsAmount(initiationIterations); processDelayedConstructions(context, components); initiationIterations++; } return components; }
/** @param constructor if all its parameter types are available in context, will be invoked and the instance will be * added to context. * @param context will be used to retrieve constructor parameters. * @return an instance of the component or null if it cannot be constructed yet. */ private Object processConstructor(final Constructor constructor, final Context context) { Object component; if (constructor.getParameterTypes().length == 0) { // Passing any empty object array avoid unnecessary array allocation. component = invokeConstructor(constructor, Strings.EMPTY_ARRAY); } else { if (areContructorParametersAvailable(constructor, context)) { final Object[] parameters = MethodInvocation.getParametersFromContext(constructor.getParameterTypes(), context); component = invokeConstructor(constructor, parameters); } else { delayedConstructions.add(constructor); return null; } } context.map(component); return component; }
/** @param constructor will be used to construct the instance. * @param parameterTypes will be used to extract constructor parameters from the context. * @return an instance of the class. * @throws RuntimeException due to reflection issues. */ protected Object createObject(final Constructor constructor, final Class<?>[] parameterTypes) { try { if (parameterTypes.length == 0) { return constructor.newInstance(Providers.EMPTY_ARRAY); } final Object[] dependencies = new Object[parameterTypes.length]; for (int index = 0, length = dependencies.length; index < length; index++) { dependencies[index] = get(parameterTypes[index], null, new ConstructorMember(constructor)); } return constructor.newInstance(dependencies); } catch (final Exception exception) { throw new RuntimeException("Unable to create an instance of: " + constructor.getDeclaringClass(), exception); } }
/** @param constructor if all its parameter types are available in context, will be invoked and the instance will be * added to context. * @param context will be used to retrieve constructor parameters. * @return an instance of the component or null if it cannot be constructed yet. */ private Object processConstructor(final Constructor constructor, final Context context) { Object component; if (constructor.getParameterTypes().length == 0) { // Passing any empty object array avoid unnecessary array allocation. component = invokeConstructor(constructor, Strings.EMPTY_ARRAY); } else { if (areContructorParametersAvailable(constructor, context)) { final Object[] parameters = MethodInvocation.getParametersFromContext(constructor.getParameterTypes(), context); component = invokeConstructor(constructor, parameters); } else { return null; } } context.map(component); return component; }
private <ES extends EntitySystem> ES getSystem(Class<ES> clazz) { ES entitySystem = engine.getSystem(clazz); if (entitySystem == null) { try { Constructor constructor = findConstructor(clazz); entitySystem = (ES) constructor.newInstance((Object[]) null); } catch (Exception ex) { Log.debug(tag, "Error instance entitySystem %s", clazz.getSimpleName()); } if (entitySystem != null) { engine.addSystem(entitySystem); } else { Log.debug(tag, "Error instance entitySystem %s", clazz.getSimpleName()); } } return entitySystem; }
public <B extends BrickBuilder> B getBrickBuilder(Class<B> clazzBuilder) { B builder = (B) bricksBuilders.get(clazzBuilder); if (builder == null) { synchronized (clazzBuilder) { try { Constructor constructor = findConstructor(clazzBuilder); builder = (B) constructor.newInstance((Object[]) null); bricksBuilders.put(clazzBuilder, builder); } catch (Exception e) { Log.debug(tag, "Error instance actuatorBuilder %s" + clazzBuilder.getSimpleName()); } } } return builder; }
/** * * @param clazz * class of the value * @param widget * the widget for the value * @param args * arguments are interpreted as a list of objects paired in * class, value ([class, value, class, value]), and they would be * use to find the right constructor */ @SuppressWarnings("unchecked") private <V extends ValueController<T, S>, T extends Actor, W extends T, S> V newValueController( Class<V> clazz, W widget, Object... args) { try { V value; if (args.length == 0) { value = ClassReflection.newInstance(clazz); } else { Class[] argsClass = new Class[args.length / 2]; Object[] argsObject = new Object[args.length / 2]; for (int i = 0; i < args.length; i += 2) { argsClass[i] = (Class) args[i]; argsObject[i] = args[i + 1]; } Constructor constructor = ClassReflection .getDeclaredConstructor(clazz, argsClass); value = (V) constructor.newInstance(argsObject); } value.build(controller, widget); return value; } catch (ReflectionException e) { Gdx.app.error("OptionsController", "No value", e); } return null; }
@SuppressWarnings("static-access") @Before public void setup() { Gdx.app = Mockito.mock(HeadlessApplication.class); when(Gdx.app.getPreferences(anyString())).thenReturn(new PreferencesStub()); config = new TwitterConfig(); PowerMockito.mockStatic(ClassReflection.class); classReflectionMock = Mockito.mock(ClassReflection.class); PowerMockito.mockStatic(Field.class); fieldMock = Mockito.mock(Field.class); PowerMockito.mockStatic(Constructor.class); constructorMock = Mockito.mock(Constructor.class); PowerMockito.mockStatic(Method.class); methodMock = Mockito.mock(Method.class); activityStub = new ActivityStub(); twitterAPIStub = new TwitterAPIStub(config); gdxStub = new GdxStub(); supportFragmentStub = new SupportFragmentStub(); fragmentStub = new FragmentStub(); gdxLifecycleListenerStub = new GdxLifecycleListenerStub(); try { Mockito.when(classReflectionMock.forName("com.badlogic.gdx.Gdx")).thenReturn(gdxStub.getClass()); Mockito.when(classReflectionMock.getField(gdxStub.getClass(), "app")).thenReturn(fieldMock); Mockito.when(fieldMock.get(null)).thenReturn(Gdx.app); } catch (ReflectionException e) { } }
private void androidPremocking() { Application mockApplication = mock(Application.class); when(mockApplication.getType()).thenReturn(Application.ApplicationType.Android); Gdx.app = mockApplication; try { mockConstructor = PowerMockito.mock(Constructor.class); mockFacebook = mock(AndroidGDXFacebook.class); mockField = mock(Field.class); mockObject = mock(Object.class); mockMethod = mock(Method.class); when(ClassReflection.forName(GDXFacebookVars.CLASSNAME_ANDROID)).thenReturn(AndroidGDXFacebook.class); when(ClassReflection.getConstructor(AndroidGDXFacebook.class, GDXFacebookConfig.class)).thenReturn(mockConstructor); when(mockConstructor.newInstance(anyObject())).thenReturn(mockFacebook); when(ClassReflection.forName("com.badlogic.gdx.Gdx")).thenReturn(Gdx.class); when(ClassReflection.getField(Gdx.class, "app")).thenReturn(mockField); when(mockField.get(null)).thenReturn(mockObject); when(ClassReflection.forName("com.badlogic.gdx.backends.android.AndroidEventListener")).thenReturn(AndroidEventListener.class); when(ClassReflection.forName("android.app.Activity")).thenReturn(Activity.class); } catch (ReflectionException e) { e.printStackTrace(); } }
/** @param constructor its parameters will be validated. * @param context contains components. * @return true if all constructor parameters can be injected. */ private static boolean areContructorParametersAvailable(final Constructor constructor, final Context context) { for (final Class<?> parameterType : constructor.getParameterTypes()) { if (!context.isPresent(parameterType) && !context.isProviderPresentFor(parameterType)) { return false; } } return true; }
/** @param constructor will be invoked. * @param parameters will be used to invoke the constructor. * @return a new instance of the class. * @throws ContextInitiationException if unable to invoke the constructor. */ private static Object invokeConstructor(final Constructor constructor, final Object[] parameters) { try { return constructor.newInstance(parameters); } catch (final ReflectionException exception) { throw new ContextInitiationException("Unable to create a new instance of class: " + constructor.getDeclaringClass() + " with constructor: " + constructor + " with parameters: " + GdxArrays.newArray(parameters), exception); } }
/** @param context used to get constructor parameters. * @param components will contain created components. */ private void processDelayedConstructions(final Context context, final Array<Object> components) { final Array<Constructor> stillMissingConstructions = GdxArrays.newArray(); for (final Constructor constructor : delayedConstructions) { final Object component = processConstructor(constructor, context); if (component != null) { components.add(component); } else { stillMissingConstructions.add(constructor); } } delayedConstructions = stillMissingConstructions; }
@Override @SuppressWarnings("unchecked") public <Component> Component create(final Class<Component> type) { final Constructor constructor = getConstructor(type); final Object component = createObject(constructor, constructor.getParameterTypes()); initiate(component); return (Component) component; }
/** @param constructors list of gathered constructors. Will be used to create the components. * @return sorting collection of components to initiate. Should be initiated. * @throws Exception due to reflection issues. */ protected Array<Initiated> gatherComponents(final PooledList<Constructor> constructors) throws Exception { final Array<Initiated> componentsToInitiate = GdxArrays.newArray(); final Array<Object> components = createComponents(constructors, componentsToInitiate); for (final Object component : components) { injectFields(component); } return componentsToInitiate; }
/** @param classes will have their constructors extracted. Should not contain interfaces or abstract classes. * @return a collection of constructors allowing to create passed classes' instances. */ protected PooledList<Constructor> gatherConstructors(final Iterable<Class<?>> classes) { final PooledList<Constructor> constructors = PooledList.newList(); for (final Class<?> componentClass : classes) { constructors.add(getConstructor(componentClass)); } return constructors; }
/** @param componentClass is requested to be constructed. * @return the first found constructor for the class. */ protected Constructor getConstructor(final Class<?> componentClass) { final Constructor[] constructors = ClassReflection.getConstructors(componentClass); if (constructors.length == 0) { throw new RuntimeException("No public constructors found for component class: " + componentClass); } return constructors[0]; }
/** @param types classes of components to initiate. * @param context will contain components mapped by their classes tree. * @return an array containing all created components. */ private Array<Object> createComponents(final Array<Class<?>> types, final Context context) { final Array<Object> components = GdxArrays.newArray(); for (final Class<?> type : types) { final Constructor[] constructors = ClassReflection.getConstructors(type); if (constructors == null || constructors.length == 0) { throw new ContextInitiationException( type + " has no available public constructors. Unable to create component."); } final Constructor constructor = constructors.length == 1 ? // Single constructor - trying to invoke it: constructors[0] : // Multiple constructors - trying to find a suitable one: findSuitableConstructor(constructors); final Object component = processConstructor(constructor, context); if (component != null) { components.add(component); } else { delayedConstructions.add(constructor); } } int initiationIterations = 0; while (GdxArrays.isNotEmpty(delayedConstructions)) { validateIterationsAmount(initiationIterations); processDelayedConstructions(context, components); initiationIterations++; } return components; }
private Constructor findConstructor (Class<T> type) { try { return ClassReflection.getConstructor(type, (Class[])null); } catch (Exception ex1) { try { Constructor constructor = ClassReflection.getDeclaredConstructor(type, (Class[])null); constructor.setAccessible(true); return constructor; } catch (ReflectionException ex2) { return null; } } }
private Constructor findConstructor(Class<T> type) { try { return ClassReflection.getConstructor(type, (Class[]) null); } catch (Exception ex1) { try { Constructor constructor = ClassReflection.getDeclaredConstructor(type, (Class[]) null); constructor.setAccessible(true); return constructor; } catch (ReflectionException ex2) { return null; } } }
private static Constructor findConstructor(Class type) { try { return ClassReflection.getConstructor(type, (Class[]) null); } catch (Exception ex1) { try { Constructor constructor = ClassReflection.getDeclaredConstructor(type, (Class[]) null); constructor.setAccessible(true); return constructor; } catch (ReflectionException ex2) { Log.debug(tag, "Error instance entitySystem %s", ex2.getMessage()); return null; } } }
private <B extends BrickBuilder> Constructor findConstructor(Class<B> type) { try { return ClassReflection.getConstructor(type, (Class[]) null); } catch (Exception ex1) { try { Constructor constructor = ClassReflection.getDeclaredConstructor(type, (Class[]) null); constructor.setAccessible(true); return constructor; } catch (ReflectionException ex2) { return null; } } }
private Constructor findConstructor(Class type) { try { return ClassReflection.getConstructor(type, (Class[]) null); } catch (Exception ex1) { try { Constructor constructor = ClassReflection.getDeclaredConstructor(type, LBBuilders.class, AssetManager.class); constructor.setAccessible(true); return constructor; } catch (ReflectionException ex2) { Log.debug(tag, "Error instance entitySystem %s", ex2.getMessage()); return null; } } }
private <T extends EntityFactory> Entity createEntity(Class<T> classFactory) { Constructor constructor = findConstructor(classFactory); T factory; try { factory = (T) constructor.newInstance(builders, assetManager); } catch (Exception ex) { Log.debug(tag, "Error instance entityFactory %s", classFactory.getSimpleName()); return null; } return factory.createEntity(); }
/** @param constructor will be wrapped. */ public ConstructorMember(final Constructor constructor) { this.constructor = constructor; }
/** @return wrapped {@link Constructor} instance. */ public Constructor getConstructor() { return constructor; }
@Override public void create () { font = new BitmapFont(); batch = new SpriteBatch(); try { Vector2 fromDefaultConstructor = ClassReflection.newInstance(Vector2.class); println("From default constructor: " + fromDefaultConstructor); Method mSet = ClassReflection.getMethod(Vector2.class, "set", float.class, float.class); mSet.invoke(fromDefaultConstructor, 10, 11); println("Set to 10/11: " + fromDefaultConstructor); Constructor copyConstroctor = ClassReflection.getConstructor(Vector2.class, Vector2.class); Vector2 fromCopyConstructor = (Vector2)copyConstroctor.newInstance(fromDefaultConstructor); println("From copy constructor: " + fromCopyConstructor); Method mMul = ClassReflection.getMethod(Vector2.class, "scl", float.class); println("Multiplied by 2; " + mMul.invoke(fromCopyConstructor, 2)); Method mNor = ClassReflection.getMethod(Vector2.class, "nor"); println("Normalized: " + mNor.invoke(fromCopyConstructor)); Vector2 fieldCopy = new Vector2(); Field fx = ClassReflection.getField(Vector2.class, "x"); Field fy = ClassReflection.getField(Vector2.class, "y"); fx.set(fieldCopy, fx.get(fromCopyConstructor)); fy.set(fieldCopy, fy.get(fromCopyConstructor)); println("Copied field by field: " + fieldCopy); Json json = new Json(); String jsonString = json.toJson(fromCopyConstructor); Vector2 fromJson = json.fromJson(Vector2.class, jsonString); println("JSON serialized: " + jsonString); println("JSON deserialized: " + fromJson); fromJson.x += 1; fromJson.y += 1; println("JSON deserialized + 1/1: " + fromJson); Object array = ArrayReflection.newInstance(int.class, 5); ArrayReflection.set(array, 0, 42); println("Array int: length=" + ArrayReflection.getLength(array) + ", access=" + ArrayReflection.get(array, 0)); array = ArrayReflection.newInstance(String.class, 5); ArrayReflection.set(array, 0, "test string"); println("Array String: length=" + ArrayReflection.getLength(array) + ", access=" + ArrayReflection.get(array, 0)); } catch (Exception e) { message = "FAILED: " + e.getMessage() + "\n"; message += e.getClass(); } }
public static ISceneGraph loadSceneGraph(FileHandle[] jsonFiles, ITimeFrameProvider time, boolean multithreading, int maxThreads) { ISceneGraph sg = null; try { Array<SceneGraphNode> nodes = new Array<SceneGraphNode>(false, 5000); for (FileHandle jsonFile : jsonFiles) { JsonReader jsonReader = new JsonReader(); InputStream is = jsonFile.read(); JsonValue model = jsonReader.parse(is); JsonValue child = model.get("data").child; while (child != null) { String clazzName = child.getString("loader"); @SuppressWarnings("unchecked") Class<Object> clazz = (Class<Object>) ClassReflection.forName(clazzName); JsonValue filesJson = child.get("files"); if (filesJson != null) { String[] files = filesJson.asStringArray(); Constructor c = ClassReflection.getConstructor(clazz); ISceneGraphLoader loader = (ISceneGraphLoader) c.newInstance(); // Init loader loader.initialize(files); // Load data Array<? extends SceneGraphNode> data = loader.loadData(); for (SceneGraphNode elem : data) { nodes.add(elem); } } child = child.next; } is.close(); } // Initialize nodes and look for octrees boolean hasOctree = false; boolean hasStarGroup = false; for (SceneGraphNode node : nodes) { node.initialize(); if (node instanceof AbstractOctreeWrapper) { hasOctree = true; AbstractOctreeWrapper aow = (AbstractOctreeWrapper) node; for (SceneGraphNode n : aow.children) { if (n instanceof StarGroup) { hasStarGroup = true; break; } } } if (node instanceof StarGroup) hasStarGroup = true; } sg = SceneGraphImplementationProvider.provider.getImplementation(multithreading, hasOctree, hasStarGroup, maxThreads); sg.initialize(nodes, time, hasOctree, hasStarGroup); } catch (Exception e) { Logger.error(e); } return sg; }
public LibGdxReflectionConstructor(Constructor constructor) { this.constructor = Objects.requireNonNull(constructor); }