Java Code Examples for com.badlogic.gdx.utils.reflect.ClassReflection

The following examples show how to use com.badlogic.gdx.utils.reflect.ClassReflection. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: talos   Source File: ScriptCompiler.java    License: Apache License 2.0 6 votes vote down vote up
public SimpleReturnScript compile (String javaString) {
	JavaSourceFromString file = new JavaSourceFromString("SimpleRunIm", javaString);
	DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
	DynamicClassesFileManager manager = new DynamicClassesFileManager(compiler.getStandardFileManager(null, null, null));

	Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
	JavaCompiler.CompilationTask task = compiler.getTask(null, manager, diagnostics, null, null, compilationUnits);

	boolean success = task.call();
	for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
		System.err.print(String.format("Script compilation error: Line: %d - %s%n", diagnostic.getLineNumber(), diagnostic.getMessage(null)));
	}
	if (success) {
		try {

			System.out.println("Compiled");
			Class clazz = manager.loader.findClass("SimpleRunIm");

			return (SimpleReturnScript)ClassReflection.newInstance(clazz);
		} catch (ReflectionException | ClassNotFoundException e) {
			e.printStackTrace();
		}
	}
	return null;
}
 
Example 2
Source Project: talos   Source File: RandomInputModule.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void attachModuleToMyInput(AbstractModule module, int mySlot, int targetSlot) {
    addInputSlot(slotCount++);
    super.attachModuleToMyInput(module, mySlot, targetSlot);

    // let's figure out the type
    if(valueType == null) {
        valueType = module.getOutputSlot(targetSlot).getValue().getClass();
    } else {
        Class newValueType = module.getOutputSlot(targetSlot).getValue().getClass();
        if(valueType != newValueType) {
            // changing value detaching all previous values
            // detach code goes here
            valueType = newValueType;
        }
    }
    // re init all previous values
    try {
        for(Slot slot : getInputSlots().values()) {
            slot.setValue((Value) ClassReflection.newInstance(valueType));
        }
        getOutputSlot(0).setValue((Value) ClassReflection.newInstance(valueType));
    } catch (ReflectionException e) {
        e.printStackTrace();
    }
}
 
Example 3
Source Project: talos   Source File: ModuleBoardWidget.java    License: Apache License 2.0 6 votes vote down vote up
public ModuleWrapper createModule (Class<? extends AbstractModule> clazz, float x, float y) {
    final AbstractModule module;
    try {
        module = ClassReflection.newInstance(clazz);

        if (TalosMain.Instance().TalosProject().getCurrentModuleGraph().addModule(module)) {
            final ModuleWrapper moduleWrapper = createModuleWrapper(module, x, y);
            moduleWrapper.setModuleToDefaults();
            module.setModuleGraph(TalosMain.Instance().TalosProject().getCurrentModuleGraph());

            TalosMain.Instance().ProjectController().setDirty();

            return moduleWrapper;
        } else {
            System.out.println("Did not create module: " + clazz.getSimpleName());
            return null;
        }
    } catch (ReflectionException e) {
        throw new GdxRuntimeException(e);
    }
}
 
Example 4
Source Project: gdx-fireapp   Source File: JsonProcessor.java    License: Apache License 2.0 6 votes vote down vote up
static <R> R process(Class<?> wantedType, String jsonString) {
    Json json = new Json();
    json.setIgnoreUnknownFields(true);
    json.setTypeName(null);
    R result = null;
    if (ClassReflection.isAssignableFrom(List.class, wantedType)
            || ClassReflection.isAssignableFrom(Map.class, wantedType)) {
        if (wantedType == List.class) {
            wantedType = ArrayList.class;
        } else if (wantedType == Map.class) {
            wantedType = HashMap.class;
        }
        json.setDefaultSerializer(new JsonListMapDeserializer(HashMap.class));
        result = (R) json.fromJson(wantedType, jsonString);
    } else {
        result = (R) json.fromJson(wantedType, jsonString);
    }
    return result;
}
 
Example 5
Source Project: gdx-fireapp   Source File: DatabaseTest.java    License: Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    mockStatic(ClassReflection.class);
    mockStatic(DatabaseReference.class);
    mockStatic(ScriptRunner.class);
    mockStatic(GwtDataPromisesManager.class);
    PowerMockito.when(ScriptRunner.class, "firebaseScript", Mockito.any(Runnable.class)).then(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            ((Runnable) invocation.getArgument(0)).run();
            return null;
        }
    });
    databaseReference = PowerMockito.mock(DatabaseReference.class);
    PowerMockito.when(DatabaseReference.of(Mockito.anyString())).thenReturn(databaseReference);
    GdxFIRApp.setAutoSubscribePromises(false);
}
 
Example 6
Source Project: gdx-fireapp   Source File: ResolverDataSnapshotList.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static List resolve(DataSnapshot dataSnapshot) {
    if (dataSnapshot.getValue() == null) {
        throw new IllegalStateException();
    }
    List result = new ArrayList<>();
    Iterable<DataSnapshot> dataSnapshots;
    if (ClassReflection.isAssignableFrom(Map.class, dataSnapshot.getValue().getClass())) {
        dataSnapshots = ((Map) dataSnapshot.getValue()).values();
    } else {
        dataSnapshots = dataSnapshot.getChildren();
    }
    for (Object o : dataSnapshots) {
        if (o instanceof DataSnapshot) {
            result.add(((DataSnapshot) o).getValue());
        } else {
            result.add(o);
        }
    }
    return result;
}
 
Example 7
Source Project: gdx-fireapp   Source File: DefaultTypeRecognizer.java    License: Apache License 2.0 6 votes vote down vote up
public static Object getDefaultValue(Class type) {
    if (isFloatingPointNumberType(type)) {
        return 0.;
    } else if (isLongNumberType(type)) {
        return 0L;
    } else if (isBooleanType(type)) {
        return false;
    } else if (isStringType(type)) {
        return "";
    } else if (isCharType(type)) {
        return '\u0000';
    } else if (ClassReflection.isAssignableFrom(Map.class, type)) {
        return new HashMap<>();
    } else if (ClassReflection.isAssignableFrom(List.class, type)) {
        return new ArrayList<>();
    } else {
        try {
            return ClassReflection.newInstance(type);
        } catch (ReflectionException e) {
            GdxFIRLogger.error(CANT_FIND_DEFAULT_VALUE_FOR_GIVEN_TYPE);
            return null;
        }
    }
}
 
Example 8
Source Project: gdx-fireapp   Source File: PlatformDistributor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates platform specific object by reflection.
 * <p>
 * Uses class names given by {@link #getAndroidClassName()} and {@link #getIOSClassName()}
 * <p>
 * If you need to run project on different platform use {@link #setMockObject(Object)} to polyfill platform object.
 *
 * @throws PlatformDistributorException Throws when something is wrong with environment
 */
@SuppressWarnings("unchecked")
protected PlatformDistributor() {
    String className = null;
    if (Gdx.app.getType() == Application.ApplicationType.Android) {
        className = getAndroidClassName();
    } else if (Gdx.app.getType() == Application.ApplicationType.iOS) {
        className = getIOSClassName();
    } else if (Gdx.app.getType() == Application.ApplicationType.WebGL) {
        className = getWebGLClassName();
    } else {
        return;
    }
    try {
        Class objClass = ClassReflection.forName(className);
        platformObject = (T) ClassReflection.getConstructor(objClass).newInstance();
    } catch (ReflectionException e) {
        throw new PlatformDistributorException("Something wrong with environment", e);
    }
}
 
Example 9
Source Project: gdx-fireapp   Source File: MapMitmConverter.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
Object doMitmConversion(Class<?> wantedType, Object data) {
    if (data == null) return null;
    // If client tell us to do map conversion and is not possible - throw exception.
    if (!isConversionPossible(data))
        throw new MapConversionNotPossibleException(CANT_DO_MAP_CONVERSION_FROM_TYPE + data.getClass().getName());
    // Check if Map is covered by data in some way, otherwise throw exception.
    if (ClassReflection.isAssignableFrom(Map.class, data.getClass())) {
        // First case - Map, do simple conversion.
        data = mapConverter.convert((Map) data, wantedType);
    } else if (ClassReflection.isAssignableFrom(List.class, data.getClass())) {
        // Second case - List, go through all elements and convert it to map.
        for (int i = ((List) data).size() - 1; i >= 0; i--) {
            Object element = ((List) data).get(i);
            if (element == null || !ClassReflection.isAssignableFrom(Map.class, element.getClass())) {
                GdxFIRLogger.log("@MapConversion: One of list value are not a Map - value was dropped. Element type: " + (element != null ? element.getClass() : "null"));
                ((List) data).remove(i);
            } else {
                ((List) data).set(i, mapConverter.convert((Map) element, wantedType));
            }
        }
    }
    return data;
}
 
Example 10
Source Project: gdx-fireapp   Source File: ResolverFIRDataSnapshotList.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
static List resolve(FIRDataSnapshot dataSnapshot) {
    List result = new ArrayList<>();
    if (dataSnapshot.value() == null) {
        throw new IllegalStateException();
    }
    NSArray nsArray;
    if (ClassReflection.isAssignableFrom(NSArray.class, dataSnapshot.value().getClass())) {
        nsArray = dataSnapshot.children().allObjects();
    } else if (ClassReflection.isAssignableFrom(NSDictionary.class, dataSnapshot.value().getClass())) {
        nsArray = ((NSDictionary) dataSnapshot.value()).allValues();
    } else {
        throw new IllegalStateException();
    }
    for (Object object : nsArray) {
        if (object instanceof FIRDataSnapshot) {
            result.add(DataProcessor.iosDataToJava(((FIRDataSnapshot) object).value()));
        } else {
            result.add(DataProcessor.iosDataToJava(object));
        }
    }
    return result;
}
 
Example 11
Source Project: skin-composer   Source File: StyleProperty.java    License: MIT License 6 votes vote down vote up
@Override
public void read(Json json, JsonValue jsonValue) {
    try {
        name = jsonValue.getString("name");
        optional = jsonValue.getBoolean("optional");
        if (jsonValue.get("value").isNumber()) {
            type = Float.TYPE;
            value = Double.parseDouble(jsonValue.getString("value"));
        } else {
            type = ClassReflection.forName(jsonValue.getString("type"));
            if (jsonValue.get("value").isNull()) {
                value = null;
            } else {
                value = jsonValue.getString("value");
            }
        }
    } catch (ReflectionException ex) {
        Gdx.app.error(getClass().toString(), "Error reading from serialized object" , ex);
        DialogFactory.showDialogErrorStatic("Read Error...","Error reading from serialized object.\n\nOpen log?");
    }
}
 
Example 12
Source Project: gdx-facebook   Source File: GDXFacebookLoaderUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void returnAndroidGDXFacebookWhenOnAndroid_core_support_v4_app_Fragment() {

    androidPremocking();

    when(ClassReflection.isAssignableFrom(Activity.class, mockObject.getClass())).thenReturn(false);

    try {
        when(ClassReflection.forName("android.support.v4.app.Fragment")).thenReturn(Fragment.class);
        when(ClassReflection.isAssignableFrom(Fragment.class, mockObject.getClass())).thenReturn(true);
        when(ClassReflection.getMethod(Fragment.class, "getActivity")).thenReturn(mockMethod);
        when(mockMethod.invoke(mockObject)).thenReturn(mockFacebook);

    } catch (ReflectionException e) {
        e.printStackTrace();
    }

    androidPostmocking();

    facebook = GDXFacebookSystem.install(new GDXFacebookConfig());
    assertTrue(facebook instanceof AndroidGDXFacebook);
}
 
Example 13
Source Project: gdx-facebook   Source File: GDXFacebookLoaderUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void returnAndroidGDXFacebookWhenOnAndroid_core_app_Fragment() {

    androidPremocking();

    when(ClassReflection.isAssignableFrom(Activity.class, mockObject.getClass())).thenReturn(false);

    try {
        when(ClassReflection.forName("android.support.v4.app.Fragment")).thenReturn(null);
        when(ClassReflection.forName("android.app.Fragment")).thenReturn(android.app.Fragment.class);

        when(ClassReflection.isAssignableFrom(android.app.Fragment.class, mockObject.getClass())).thenReturn(true);
        when(ClassReflection.getMethod(android.app.Fragment.class, "getActivity")).thenReturn(mockMethod);
        when(mockMethod.invoke(mockObject)).thenReturn(mockFacebook);

    } catch (ReflectionException e) {
        e.printStackTrace();
    }

    androidPostmocking();

    facebook = GDXFacebookSystem.install(new GDXFacebookConfig());
    assertTrue(facebook instanceof AndroidGDXFacebook);
}
 
Example 14
Source Project: gdx-facebook   Source File: GDXFacebookLoaderUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 15
Source Project: gdx-facebook   Source File: GDXFacebookLoaderUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 16
Source Project: gdx-facebook   Source File: GDXFacebookLoaderUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 17
Source Project: riiablo   Source File: Keys.java    License: Apache License 2.0 6 votes vote down vote up
private static Collection<Throwable> addTo(KeyMapper keyMapper, Class<?> clazz, Collection<Throwable> throwables) {
  for (Field field : ClassReflection.getFields(clazz)) {
    if (MappedKey.class.isAssignableFrom(field.getType())) {
      try {
        keyMapper.add((MappedKey) field.get(null));
      } catch (Throwable t) {
        throwables.add(t);
      }
    }
  }

  for (Class<?> subclass : clazz.getClasses()) {
    addTo(keyMapper, subclass, throwables);
  }

  return throwables;
}
 
Example 18
Source Project: riiablo   Source File: Cvars.java    License: Apache License 2.0 6 votes vote down vote up
private static Collection<Throwable> addTo(CvarManager cvarManager, Class<?> clazz, Collection<Throwable> throwables) {
  for (Field field : ClassReflection.getFields(clazz)) {
    if (Cvar.class.isAssignableFrom(field.getType())) {
      try {
        cvarManager.add((Cvar) field.get(null));
      } catch (Throwable t) {
        throwables.add(t);
      }
    }
  }

  for (Class<?> subclass : clazz.getClasses()) {
    addTo(cvarManager, subclass, throwables);
  }

  return throwables;
}
 
Example 19
Source Project: gdx-dialogs   Source File: AndroidGDXDialogs.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public <T> T newDialog(Class<T> cls) {
	String className = cls.getName();
	if (registeredDialogs.containsKey(className)) {

		try {
			final Class<T> dialogClazz = ClassReflection.forName(registeredDialogs.get(className));

			Object dialogObject = ClassReflection.getConstructor(dialogClazz, Activity.class).newInstance(activity);

			return dialogClazz.cast(dialogObject);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	throw new RuntimeException(cls.getName() + "is not registered.");
}
 
Example 20
Source Project: gdx-dialogs   Source File: GDXDialogsSystem.java    License: Apache License 2.0 6 votes vote down vote up
private void installDesktopGDXDialogs() {
	if (Gdx.app.getType() != ApplicationType.Desktop) {
		showDebugSkipInstall(ApplicationType.Desktop.name());
		return;
	}
	try {

		final Class<?> dialogManagerClazz = ClassReflection.forName("de.tomgrill.gdxdialogs.desktop.DesktopGDXDialogs");

		Object dialogManager = ClassReflection.getConstructor(dialogManagerClazz).newInstance();

		this.gdxDialogs = (GDXDialogs) dialogManager;

		showDebugInstallSuccessful(ApplicationType.Desktop.name());

	} catch (ReflectionException e) {
		showErrorInstall(ApplicationType.Desktop.name(), "desktop");
		e.printStackTrace();
	}

}
 
Example 21
Source Project: gdx-dialogs   Source File: GDXDialogsSystem.java    License: Apache License 2.0 6 votes vote down vote up
private void installHTMLGDXDialogs() {
	if (Gdx.app.getType() != ApplicationType.WebGL) {
		showDebugSkipInstall(ApplicationType.WebGL.name());
		return;
	}

	try {

		final Class<?> dialogManagerClazz = ClassReflection.forName("de.tomgrill.gdxdialogs.html.HTMLGDXDialogs");
		Object dialogManager = ClassReflection.getConstructor(dialogManagerClazz).newInstance();

		this.gdxDialogs = (GDXDialogs) dialogManager;
		showDebugInstallSuccessful(ApplicationType.WebGL.name());

	} catch (ReflectionException e) {
		showErrorInstall(ApplicationType.WebGL.name(), "html");
		e.printStackTrace();
	}

}
 
Example 22
Source Project: gdx-ai   Source File: MessageDispatcher.java    License: Apache License 2.0 6 votes vote down vote up
/** Registers a listener for the specified message code. Messages without an explicit receiver are broadcasted to all its
 * registered listeners.
 * @param listener the listener to add
 * @param msg the message code */
public void addListener (Telegraph listener, int msg) {
	Array<Telegraph> listeners = msgListeners.get(msg);
	if (listeners == null) {
		// Associate an empty unordered array with the message code
		listeners = new Array<Telegraph>(false, 16);
		msgListeners.put(msg, listeners);
	}
	listeners.add(listener);

	// Dispatch messages from registered providers
	Array<TelegramProvider> providers = msgProviders.get(msg);
	if (providers != null) {
		for (int i = 0, n = providers.size; i < n; i++) {
			TelegramProvider provider = providers.get(i);
			Object info = provider.provideMessageInfo(msg, listener);
			if (info != null) {
				Telegraph sender = ClassReflection.isInstance(Telegraph.class, provider) ? (Telegraph)provider : null;
				dispatchMessage(0, sender, listener, msg, info, false);
			}
		}
	}
}
 
Example 23
Source Project: gdx-ai   Source File: Task.java    License: Apache License 2.0 6 votes vote down vote up
/** Clones this task to a new one. If you don't specify a clone strategy through {@link #TASK_CLONER} the new task is
 * instantiated via reflection and {@link #copyTo(Task)} is invoked.
 * @return the cloned task
 * @throws TaskCloneException if the task cannot be successfully cloned. */
@SuppressWarnings("unchecked")
public Task<E> cloneTask () {
	if (TASK_CLONER != null) {
		try {
			return TASK_CLONER.cloneTask(this);
		} catch (Throwable t) {
			throw new TaskCloneException(t);
		}
	}
	try {
		Task<E> clone = copyTo(ClassReflection.newInstance(this.getClass()));
		clone.guard = guard == null ? null : guard.cloneTask();
		return clone;
	} catch (ReflectionException e) {
		throw new TaskCloneException(e);
	}
}
 
Example 24
Source Project: gdx-ai   Source File: BehaviorTreeParser.java    License: Apache License 2.0 6 votes vote down vote up
private Metadata findMetadata (Class<?> clazz) {
	Metadata metadata = metadataCache.get(clazz);
	if (metadata == null) {
		Annotation tca = ClassReflection.getAnnotation(clazz, TaskConstraint.class);
		if (tca != null) {
			TaskConstraint taskConstraint = tca.getAnnotation(TaskConstraint.class);
			ObjectMap<String, AttrInfo> taskAttributes = new ObjectMap<String, AttrInfo>();
			Field[] fields = ClassReflection.getFields(clazz);
			for (Field f : fields) {
				Annotation a = f.getDeclaredAnnotation(TaskAttribute.class);
				if (a != null) {
					AttrInfo ai = new AttrInfo(f.getName(), a.getAnnotation(TaskAttribute.class));
					taskAttributes.put(ai.name, ai);
				}
			}
			metadata = new Metadata(taskConstraint.minChildren(), taskConstraint.maxChildren(), taskAttributes);
			metadataCache.put(clazz, metadata);
		}
	}
	return metadata;
}
 
Example 25
Source Project: gdx-vfx   Source File: Scene2dUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** Injects actors from group into target's fields annotated with {@link InjectActor} using reflection. */
public static void injectActorFields(Object target, Group group) {
    Class<?> handledClass = target.getClass();
    while (handledClass != null && !handledClass.equals(Object.class)) {
        for (final Field field : ClassReflection.getDeclaredFields(handledClass)) {
            if (field != null && field.isAnnotationPresent(InjectActor.class)) {
                try {
                    InjectActor annotation = field.getDeclaredAnnotation(InjectActor.class).getAnnotation(InjectActor.class);
                    String actorName = annotation.value();
                    if (actorName.length() == 0) {
                        actorName = field.getName();
                    }
                    Actor actor = group.findActor(actorName);
                    if (actor == null && actorName.equals(group.getName())) {
                        actor = group;
                    }
                    if (actor == null) {
                        Gdx.app.error(TAG_INJECT_FIELDS, "Can't find actor with name: " + actorName + " in group: " + group + " to inject into: " + target);
                    } else {
                        field.setAccessible(true);
                        field.set(target, actor);
                    }
                } catch (final ReflectionException exception) {
                    Gdx.app.error(TAG_INJECT_FIELDS, "Unable to set value into field: " + field + " of object: " + target, exception);
                }
            }
        }
        handledClass = handledClass.getSuperclass();
    }
}
 
Example 26
Source Project: talos   Source File: ModuleBoardWidget.java    License: Apache License 2.0 5 votes vote down vote up
public <T extends AbstractModule> ModuleWrapper createModuleWrapper (T module, float x, float y) {
    ModuleWrapper<T> moduleWrapper = null;

    if (module == null) return null;

    Class<T> moduleClazz = (Class<T>)module.getClass();

    try {
        moduleWrapper = ClassReflection.newInstance(WrapperRegistry.get(moduleClazz));
        int id = getUniqueIdForModuleWrapper();
        moduleWrapper.setModule(module);
        moduleWrapper.setId(id);
        module.setIndex(id);
        moduleWrapper.setBoard(this);

        tmp.set(x, Gdx.graphics.getHeight() - y);
        moduleContainer.screenToLocalCoordinates(tmp);

        moduleWrapper.setPosition(tmp.x - moduleWrapper.getWidth()/2f, tmp.y - moduleWrapper.getHeight()/2f);
        getModuleWrappers().add(moduleWrapper);
        moduleContainer.addActor(moduleWrapper);

        selectWrapper(moduleWrapper);
    } catch (ReflectionException e) {
        e.printStackTrace();
    }


    // check if there was connect request
    tryAndConnectLasCC(moduleWrapper);


    return moduleWrapper;
}
 
Example 27
Source Project: talos   Source File: ModuleListPopup.java    License: Apache License 2.0 5 votes vote down vote up
private void registerModule(XmlReader.Element module) {
    try {
        Class moduleClazz = ClassReflection.forName("com.talosvfx.talos.runtime.modules." + module.getText());
        Class wrapperClazz =ClassReflection.forName("com.talosvfx.talos.editor.wrappers." + module.getAttribute("wrapper"));
        WrapperRegistry.reg(moduleClazz, wrapperClazz);
        TalosMain.Instance().moduleNames.put(wrapperClazz, module.getAttribute("name"));
    } catch (ReflectionException e) {
        e.printStackTrace();
    }

    WrapperRegistry.reg(EmitterModule.class, EmitterModuleWrapper.class);
}
 
Example 28
Source Project: gdx-gltf   Source File: PixmapBinaryLoaderHack.java    License: Apache License 2.0 5 votes vote down vote up
public static Pixmap load(byte [] encodedData, int offset, int len){
	if(Gdx.app.getType() == ApplicationType.WebGL){
		throw new GdxRuntimeException("load pixmap from bytes not supported for WebGL");
	}else{
		// call new Pixmap(encodedData, offset, len); via reflection to
		// avoid compilation error with GWT.
		try {
			return (Pixmap)ClassReflection.getConstructor(Pixmap.class, byte[].class, int.class, int.class).newInstance(encodedData, offset, len);
		} catch (ReflectionException e) {
			throw new GdxRuntimeException(e);
		}
	}
}
 
Example 29
Source Project: gdx-gltf   Source File: GLTFBinaryExporter.java    License: Apache License 2.0 5 votes vote down vote up
public static void savePNG(FileHandle file, Pixmap pixmap){
	if(Gdx.app.getType() == ApplicationType.WebGL){
		throw new GdxRuntimeException("saving pixmap not supported for WebGL");
	}else{
		// call PixmapIO.writePNG(file, pixmap); via reflection to
		// avoid compilation error with GWT.
		try {
			Class pixmapIO = ClassReflection.forName("com.badlogic.gdx.graphics.PixmapIO");
			Method pixmapIO_writePNG = ClassReflection.getMethod(pixmapIO, "writePNG", FileHandle.class, Pixmap.class);
			pixmapIO_writePNG.invoke(null, file, pixmap);
		} catch (ReflectionException e) {
			throw new GdxRuntimeException(e);
		} 
	}
}
 
Example 30
Source Project: gdx-fireapp   Source File: StringGeneratorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void dataToString_primitve() {
    // Given
    PowerMockito.mockStatic(ClassReflection.class);
    Mockito.when(ClassReflection.isPrimitive(Mockito.any(Class.class))).thenReturn(true);
    Object arg = 3;

    // When
    Object data = StringGenerator.dataToString(arg);

    // Then
    Assert.assertEquals(arg.toString(), data);
}