com.badlogic.gdx.utils.reflect.ReflectionException Java Examples

The following examples show how to use com.badlogic.gdx.utils.reflect.ReflectionException. 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 File: ScriptCompiler.java    From talos with 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 File: Task.java    From gdx-ai with 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 #3
Source File: BehaviorTreeViewer.java    From gdx-ai with Apache License 2.0 6 votes vote down vote up
private static void appendFieldString (StringBuilder sb, Task<?> task, TaskAttribute ann, Field field) {
	// prefer name from annotation if there is one
	String name = ann.name();
	if (name == null || name.length() == 0) name = field.getName();
	Object value;
	try {
		field.setAccessible(true);
		value = field.get(task);
	} catch (ReflectionException e) {
		Gdx.app.error("", "Failed to get field", e);
		return;
	}
	sb.append(name).append(":");
	Class<?> fieldType = field.getType();
	if (fieldType.isEnum() || fieldType == String.class) {
		sb.append('\"').append(value).append('\"');
	} else if (Distribution.class.isAssignableFrom(fieldType)) {
		sb.append('\"').append(DAs.toString((Distribution)value)).append('\"');
	} else
		sb.append(value);
}
 
Example #4
Source File: ActionDetector.java    From bladecoder-adventure-engine with Apache License 2.0 6 votes vote down vote up
public static Action create(String name, HashMap<String, String> params) {
	Class<?> c = actions.get(name);
	
	if(c == null) {
		// Search in custom actions
		c = getCustomActionByName(name);
	}

	if (c == null) {
		EditorLogger.error("Action with name '" + name + "' not found.");

		return null;
	}

	try {
		return ActionFactory.create(c.getName(), params);
	} catch (ClassNotFoundException | ReflectionException e) {
		EditorLogger.error("Action with name '" + name + "' not found.");

		return null;
	}
}
 
Example #5
Source File: GDXDialogsSystem.java    From gdx-dialogs with 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 #6
Source File: GDXDialogsSystem.java    From gdx-dialogs with 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 #7
Source File: GDXFacebookLoaderUnitTests.java    From gdx-facebook with 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 #8
Source File: GDXFacebookLoaderUnitTests.java    From gdx-facebook with 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 #9
Source File: GDXFacebookLoaderUnitTests.java    From gdx-facebook with 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 #10
Source File: GDXFacebookLoaderUnitTests.java    From gdx-facebook with 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 #11
Source File: GDXFacebookLoaderUnitTests.java    From gdx-facebook with 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 #12
Source File: StyleProperty.java    From skin-composer with 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 #13
Source File: PlatformDistributor.java    From gdx-fireapp with 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 #14
Source File: DefaultTypeRecognizer.java    From gdx-fireapp with 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 #15
Source File: RandomInputModule.java    From talos with 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 #16
Source File: ModuleBoardWidget.java    From talos with 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 #17
Source File: Reflection.java    From shattered-pixel-dungeon with GNU General Public License v3.0 5 votes vote down vote up
public static Class forName( String name ){
	try {
		return ClassReflection.forName( name );
	} catch (ReflectionException e) {
		Game.reportException(e);
		return null;
	}
}
 
Example #18
Source File: Engine.java    From ashley with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new {@link Component}. To use that method your components must have a visible no-arg constructor
 */
public <T extends Component> T createComponent (Class<T> componentType) {
	try {
		return ClassReflection.newInstance(componentType);
	} catch (ReflectionException e) {
		return null;
	}
}
 
Example #19
Source File: Reflection.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 5 votes vote down vote up
public static Class forName( String name ){
	try {
		return ClassReflection.forName( name );
	} catch (ReflectionException e) {
		Game.reportException(e);
		return null;
	}
}
 
Example #20
Source File: Reflection.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 5 votes vote down vote up
public static <T> T newInstance( Class<T> cls ){
	try {
		return ClassReflection.newInstance(cls);
	} catch (ReflectionException e) {
		Game.reportException(e);
		return null;
	}
}
 
Example #21
Source File: BehaviorTreeParser.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
void addImport (String alias, String task) {
	if (task == null) throw new GdxRuntimeException("import: missing task class name.");
	if (alias == null) {
		Class<?> clazz = null;
		try {
			clazz = ClassReflection.forName(task);
		} catch (ReflectionException e) {
			throw new GdxRuntimeException("import: class not found '" + task + "'");
		}
		alias = clazz.getSimpleName();
	}
	String className = getImport(alias);
	if (className != null) throw new GdxRuntimeException("import: alias '" + alias + "' previously defined already.");
	userImports.put(alias, task);
}
 
Example #22
Source File: BehaviorTreeParser.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
private void setField (Field field, Task<E> task, Object value) {
	field.setAccessible(true);
	Object valueObject = castValue(field, value);
	if (valueObject == null) throwAttributeTypeException(getCurrentTask().name, field.getName(), field.getType().getSimpleName());
	try {
		field.set(task, valueObject);
	} catch (ReflectionException e) {
		throw new GdxRuntimeException(e);
	}
}
 
Example #23
Source File: BehaviorTreeParser.java    From gdx-ai with Apache License 2.0 5 votes vote down vote up
private Field getField (Class<?> clazz, String name) {
	try {
		return ClassReflection.getField(clazz, name);
	} catch (ReflectionException e) {
		throw new GdxRuntimeException(e);
	}
}
 
Example #24
Source File: Scene2dUtils.java    From gdx-vfx with 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 #25
Source File: ActionFactory.java    From bladecoder-adventure-engine with Apache License 2.0 5 votes vote down vote up
public static Action create(String tag, HashMap<String, String> params)
		throws ClassNotFoundException, ReflectionException {

	Action a = null;

	Class<?> c = tagToClass.get(tag);

	if (c == null) {
		c = Class.forName(tag, true, loader);
	}

	a = (Action) ClassReflection.newInstance(c);

	if (params != null) {

		for (String key : params.keySet()) {
			String value = params.get(key);

			try {
				ActionUtils.setParam(a, key, value);
			} catch (NoSuchFieldException | SecurityException | IllegalArgumentException
					| IllegalAccessException e) {
				EngineLogger.error("Error Setting Action Param - Action:" + tag + " Param: " + key + " Value: "
						+ value + " Msg: NOT FOUND " + e.getMessage());
			}
		}
	}

	return a;
}
 
Example #26
Source File: Reflection.java    From shattered-pixel-dungeon with GNU General Public License v3.0 5 votes vote down vote up
public static <T> T newInstance( Class<T> cls ){
	try {
		return ClassReflection.newInstance(cls);
	} catch (ReflectionException e) {
		Game.reportException(e);
		return null;
	}
}
 
Example #27
Source File: ModuleBoardWidget.java    From talos with 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 #28
Source File: ModuleListPopup.java    From talos with 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 #29
Source File: GDXDialogsSystem.java    From gdx-dialogs with Apache License 2.0 5 votes vote down vote up
private void installGdxReflections() {

		try {
			gdxClazz = ClassReflection.forName("com.badlogic.gdx.Gdx");
			gdxAppObject = ClassReflection.getField(gdxClazz, "app").get(null);

		} catch (ReflectionException e) {
			e.printStackTrace();
			throw new RuntimeException("No libGDX environment. \n");
		}

	}
 
Example #30
Source File: PixmapBinaryLoaderHack.java    From gdx-gltf with 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);
		}
	}
}