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

The following examples show how to use com.badlogic.gdx.utils.reflect.ClassReflection. 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: BehaviorTreeParser.java    From gdx-ai with 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 #2
Source File: ResolverDataSnapshotList.java    From gdx-fireapp with 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 #3
Source File: DatabaseTest.java    From gdx-fireapp with 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 #4
Source File: JsonProcessor.java    From gdx-fireapp with 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 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 #6
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 #7
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 #8
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 #9
Source File: MapMitmConverter.java    From gdx-fireapp with 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 File: ResolverFIRDataSnapshotList.java    From gdx-fireapp with 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 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 #12
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 #13
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 #14
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 #15
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 #16
Source File: MessageDispatcher.java    From gdx-ai with 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 #17
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 #18
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 #19
Source File: AndroidGDXDialogs.java    From gdx-dialogs with 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 File: Cvars.java    From riiablo with 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 #21
Source File: Keys.java    From riiablo with 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 #22
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 #23
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 #24
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 #25
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 #26
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 #27
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 #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: RunTransactionValidator.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Override
public void validate(Array<Object> arguments) {
    if (arguments.size < 2)
        throw new IllegalArgumentException(MESSAGE1);
    if (!(arguments.get(0) instanceof Class))
        throw new IllegalArgumentException(MESSAGE2);
    if (!(arguments.get(1) instanceof Function))
        throw new IllegalArgumentException(MESSAGE3);
    if (ClassReflection.isAssignableFrom(Number.class, (Class) arguments.get(0))
            && arguments.get(0) != Double.class
            && arguments.get(0) != Long.class
    ) {
        throw new IllegalArgumentException(NUMBER_TYPE_SHOULD_BE_LONG_OR_DOUBLE);
    }
}
 
Example #30
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");
		}

	}