本文将为您提供关于JavaReflection-对象不是声明类的实例的详细介绍,我们还将为您解释java有哪些不是对象的数据的相关知识,同时,我们还将为您提供关于com.badlogic.gdx.ut
本文将为您提供关于Java Reflection-对象不是声明类的实例的详细介绍,我们还将为您解释java有哪些不是对象的数据的相关知识,同时,我们还将为您提供关于com.badlogic.gdx.utils.reflect.ArrayReflection的实例源码、com.badlogic.gdx.utils.reflect.ClassReflection的实例源码、com.badlogic.gdx.utils.reflect.ReflectionException的实例源码、com.google.common.reflect.Reflection的实例源码的实用信息。
本文目录一览:- Java Reflection-对象不是声明类的实例(java有哪些不是对象的数据)
- com.badlogic.gdx.utils.reflect.ArrayReflection的实例源码
- com.badlogic.gdx.utils.reflect.ClassReflection的实例源码
- com.badlogic.gdx.utils.reflect.ReflectionException的实例源码
- com.google.common.reflect.Reflection的实例源码
Java Reflection-对象不是声明类的实例(java有哪些不是对象的数据)
这个问题在Google上到处都有,但我仍然遇到问题。这就是我想要做的。因此,就像标题状态一样,我遇到了“对象不是声明类的实例”错误。有任何想法吗?谢谢!
Main.java
Class<?> base = Class.forName("server.functions.TestFunction");Method serverMethod = base.getMethod("execute", HashMap.class);serverMethod.invoke(base, new HashMap<String, String>());
TestFunction.java
package server.functions;import java.util.HashMap;import java.util.Map;import server.*;public class TestFunction extends ServerBase { public String execute(HashMap<String, String> params) { return "Test function successfully called"; }}
答案1
小编典典您正在使用该类调用该方法,但需要一个实例。试试这个:
serverMethod.invoke(base.newInstance(), new HashMap<String, String>());
com.badlogic.gdx.utils.reflect.ArrayReflection的实例源码
/** Reallocate a buffer. */ public static <T> T[] reallocateBuffer(Class<T> klass,T[] oldBuffer,int oldCapacity,int newCapacity) { assert (newCapacity > oldCapacity); @SuppressWarnings("unchecked") T[] newBuffer = (T[]) ArrayReflection.newInstance(klass,newCapacity); if (oldBuffer != null) { System.arraycopy(oldBuffer,newBuffer,oldCapacity); } for (int i = oldCapacity; i < newCapacity; i++) { try { newBuffer[i] = ClassReflection.newInstance(klass); } catch (Exception e) { throw new RuntimeException(e); } } return newBuffer; }
@Override public <T> T[] getAll(Class<T> clazz) { Object[] got = gotAll.get(clazz); if (got != null) { return (T[]) got; } Array<ISystem> matching = cache.getNext(); matching.clear(); for (int i = 0; i < systems.size; i++) { ISystem system = systems.items[i]; if (clazz.isAssignableFrom(system.getClass())) { matching.add(system); } } T[] array = (T[]) ArrayReflection.newInstance(clazz,matching.size); System.arraycopy(matching.items,array,array.length); gotAll.put(clazz,array); return array; }
/** Creates a new backing array with the specified size containing the current items. */ protected T[] resize (int newSize) { T[] items = this.items; T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(),newSize); System.arraycopy(items,newItems,Math.min(size,newItems.length)); this.items = newItems; return newItems; }
/** Creates a new backing array with the specified capacity containing the current items. * @param newCapacity the new capacity */ protected void resize (int newCapacity) { @SuppressWarnings("unchecked") T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(),newCapacity); if (tail > head) { System.arraycopy(items,head,size); } else if (size > 0) { // NOTE: when head == tail the buffer can be empty or full System.arraycopy(items,items.length - head); System.arraycopy(items,items.length - head,tail); } head = 0; tail = size; items = newItems; }
protected void resize (int newSize) { K[] newKeys = (K[])ArrayReflection.newInstance(keys.getClass().getComponentType(),newSize); System.arraycopy(keys,newKeys,newKeys.length)); this.keys = newKeys; V[] newValues = (V[])ArrayReflection.newInstance(values.getClass().getComponentType(),newSize); System.arraycopy(values,newValues,newValues.length)); this.values = newValues; }
/** Creates a new backing array with the specified size containing the current items. */ protected T[] resize (int newSize) { T[] items = this.items; T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(),newItems.length)); this.items = newItems; return newItems; }
@SuppressWarnings("unchecked") <T> T[] requestParticleBuffer(Class<T> klass,T[] buffer) { if (buffer == null) { buffer = (T[]) ArrayReflection.newInstance(klass,m_internalAllocatedCapacity); for (int i = 0; i < m_internalAllocatedCapacity; i++) { try { buffer[i] = ClassReflection.newInstance(klass); } catch (Exception e) { throw new RuntimeException(e); } } } return buffer; }
/** * Creates a new backing array with the specified size containing the current items. * * @param newSize * @return */ protected T[] resize(int newSize) { T[] items = this.items; T[] newItems = (T[]) ArrayReflection.newInstance(items.getClass().getComponentType(),newItems.length)); this.items = newItems; return newItems; }
protected void resize(int newSize) { K[] newKeys = (K[]) ArrayReflection.newInstance(keys.getClass().getComponentType(),newKeys.length)); this.keys = newKeys; V[] newValues = (V[]) ArrayReflection.newInstance(values.getClass().getComponentType(),newValues.length)); this.values = newValues; }
/** * Creates a new backing array with the specified size containing the * current items. */ protected T[] resize(int newSize) { T[] items = this.items; T[] newItems = (T[]) ArrayReflection.newInstance(items.getClass().getComponentType(),newItems.length)); this.items = newItems; return newItems; }
/** Creates a new backing array with the specified capacity containing the current items. * @param newCapacity the new capacity */ protected void resize (int newCapacity) { @SuppressWarnings("unchecked") T[] newItems = (T[])ArrayReflection.newInstance(items.getClass().getComponentType(),tail); } head = 0; tail = size; items = newItems; }
@Override public Object evaluate(VarsContext context) throws ExpressionEvaluationException { // First arg should be the container object // First argument should always be a collection or similar Object arg1 = first().evaluate(context); if (arg1.getClass().isArray()) { return ArrayReflection.getLength(arg1); } else if (arg1 instanceof Array) { Array array = (Array) arg1; return array.size; } else if (arg1 instanceof Map) { Map map = (Map) arg1; return map.size(); } else if (arg1 instanceof Collection) { Collection collection = (Collection) arg1; return collection.size(); } else if (arg1 instanceof Iterable) { Iterable iterable = (Iterable) arg1; int i = 0; for (Object object : iterable) { i++; } return i; } else { throw new ExpressionEvaluationException( "Could not evaluate " + getName() + ". Revise the first argument is a collection,iterable or map.",this); } }
/** Creates a new array with {@link #items} of the specified type. * @param ordered If false,methods that remove elements may change the order of other elements in the array,which avoids a * memory copy. * @param capacity Any elements added beyond this will cause the backing array to be grown. */ public Array (boolean ordered,int capacity,Class arrayType) { this.ordered = ordered; items = (T[])ArrayReflection.newInstance(arrayType,capacity); }
public <V> V[] toArray (Class type) { V[] result = (V[])ArrayReflection.newInstance(type,size); System.arraycopy(items,result,size); return result; }
@Override @SuppressWarnings("unchecked") public Type[] getArray(final int size) { return (Type[]) ArrayReflection.newInstance(arrayType,size); }
public ObjectChannel (int id,int strideSize,int size,Class<T> type) { super(id,ArrayReflection.newInstance(type,size*strideSize),strideSize); componentType = type; this.data = (T[]) super.data; }
@Override public void setCapacity (int requiredCapacity) { T[] newData = (T[]) ArrayReflection.newInstance(componentType,strideSize * requiredCapacity); System.arraycopy(data,newData,Math.min(data.length,newData.length)); super.data = data = newData; }
/** Creates a new map with {@link #keys} and {@link #values} of the specified type. * @param ordered If false,methods that remove elements may change the order of other elements in the arrays,which avoids a * memory copy. * @param capacity Any elements added beyond this will cause the backing arrays to be grown. */ public ArrayMap (boolean ordered,Class keyArrayType,Class valueArrayType) { this.ordered = ordered; keys = (K[])ArrayReflection.newInstance(keyArrayType,capacity); values = (V[])ArrayReflection.newInstance(valueArrayType,capacity); }
/** Creates a new array with {@link #items} of the specified type. * @param ordered If false,capacity); }
public <V> V[] toArray (Class type) { V[] result = (V[])ArrayReflection.newInstance(type,size); return result; }
@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,42); println("Array int: length=" + ArrayReflection.getLength(array) + ",access=" + ArrayReflection.get(array,0)); array = ArrayReflection.newInstance(String.class,"test string"); println("Array String: length=" + ArrayReflection.getLength(array) + ",0)); } catch (Exception e) { message = "Failed: " + e.getMessage() + "\n"; message += e.getClass(); } }
public <V> V[] toArray(Class type) { V[] result = (V[]) ArrayReflection.newInstance(type,size); return result; }
public <V> V[] toArray(Class type) { V[] result = (V[]) ArrayReflection.newInstance(type,size); return result; }
public ArrayIterable(Object anArray) { this.arrayLength = ArrayReflection.getLength(anArray); this.innerArray = anArray; }
@Override public Expression next() { currentElement.value = ArrayReflection.get(innerArray,arrayPosition++); return currentElement; }
@Override public Object evaluate(VarsContext context) throws ExpressionEvaluationException { // Second argument,if present,should be the index of the element to // retrieve. // If not present,the first (0) element is returned int index = 0; Object indexObject = null; if (children.size() > 1) { Object arg2 = second().evaluate(context); if (arg2 instanceof Number) { index = ((Number) arg2).intValue(); } else { indexObject = arg2; } } // First argument should always be a collection or similar Object arg1 = first().evaluate(context); try { if (arg1.getClass().isArray()) { return ArrayReflection.get(arg1,index); } else if (arg1 instanceof Array) { Array array = (Array) arg1; return array.get(index); } else if (arg1 instanceof List) { List list = (List) arg1; return list.get(index); } else if (arg1 instanceof Map) { Map map = (Map) arg1; return map.get(indexObject); } else if (arg1 instanceof Collection) { Collection collection = (Collection) arg1; return collection.toArray()[index]; } else if (arg1 instanceof Iterable) { Iterable iterable = (Iterable) arg1; int i = 0; for (Object object : iterable) { if (index == i++) { return object; } } } else { throw new ExpressionEvaluationException( "Could not evaluate " + getName() + ". Revise the first argument is a collection,iterable or map,and the second argument is a valid element position (for collections,arrays,iterables) or key (for maps)",this); } } catch (Exception e) { throw new ExpressionEvaluationException("Problem accessing index " + index + " + in " + arg1,this,e); } return null; }
/** * Creates a new array with {@link #items} of the specified type. * * @param ordered If false,which * avoids a memory copy. * @param capacity Any elements added beyond this will cause the backing array to be grown. * @param arrayType */ public Array(boolean ordered,Class arrayType) { this.ordered = ordered; items = (T[]) ArrayReflection.newInstance(arrayType,capacity); }
/** * Creates a new map with {@link #keys} and {@link #values} of the specified * type. * * @param ordered * If false,methods that remove elements may change the order of * other elements in the arrays,which avoids a memory copy. * @param capacity * Any elements added beyond this will cause the backing arrays * to be grown. */ public ArrayMap(boolean ordered,Class valueArrayType) { this.ordered = ordered; keys = (K[]) ArrayReflection.newInstance(keyArrayType,capacity); values = (V[]) ArrayReflection.newInstance(valueArrayType,capacity); }
/** * Creates a new array with {@link #items} of the specified type. * * @param ordered * If false,methods that remove elements may change the order of * other elements in the array,which avoids a memory copy. * @param capacity * Any elements added beyond this will cause the backing array to * be grown. */ public Array(boolean ordered,capacity); }
com.badlogic.gdx.utils.reflect.ClassReflection的实例源码
@Override public Object read(ByteBuffer byteBuffer) { try { byte id = byteBuffer.get(); if(id == -2){ return FrameworkSerializer.read(byteBuffer); }else { Class<?> type = Registrator.getByID(id); Packet packet = (Packet) ClassReflection.newInstance(type); packet.read(byteBuffer); return packet; } }catch (ReflectionException e){ throw new RuntimeException(e); } }
void save(SaveSlot slot){ Vars.ui.loadfrag.show("$text.saveload"); Timers.runTask(5f,() -> { hide(); Vars.ui.loadfrag.hide(); try{ slot.save(); }catch(Throwable e){ e = (e.getCause() == null ? e : e.getCause()); Vars.ui.showError("[orange]"+Bundles.get("text.savefail")+"\n[white]" + ClassReflection.getSimpleName(e.getClass()) + ": " + e.getMessage() + "\n" + "at " + e.getStackTrace()[0].getFileName() + ":" + e.getStackTrace()[0].getLineNumber()); } }); }
private void runExitSave(){ if(Vars.control.getSaves().getCurrent() == null || !Vars.control.getSaves().getCurrent().isAutosave()){ GameState.set(State.menu); Vars.control.getTutorial().reset(); return; } Vars.ui.loadfrag.show("$text.saveload"); Timers.runTask(5f,() -> { Vars.ui.loadfrag.hide(); try{ Vars.control.getSaves().getCurrent().save(); }catch(Throwable e){ e = (e.getCause() == null ? e : e.getCause()); Vars.ui.showError("[orange]"+ Bundles.get("text.savefail")+"\n[white]" + ClassReflection.getSimpleName(e.getClass()) + ": " + e.getMessage() + "\n" + "at " + e.getStackTrace()[0].getFileName() + ":" + e.getStackTrace()[0].getLineNumber()); } GameState.set(State.menu); }); }
/** * Returns the Class matching the name of the JsonValue,or null if there is no match or it's nameless. */ private Class getClass(JsonValue value,ObjectMap<String,Class> tagsToClasses) { if (value.name() != null && value.name().length() > 0) { String className = value.name(); Class type = tagsToClasses.get(className); if (type == null) { try { type = ClassReflection.forName(className); } catch (ReflectionException ex) { type = null; } } return type; } return null; }
private OrderedMap<String,Field> getStaticFields(Class type) { if (staticFields.containsKey(type)) return staticFields.get(type); Field[] fields = ClassReflection.getDeclaredFields(type); OrderedMap<String,Field> nametoField = new OrderedMap(fields.length); for (Field field : fields) { if (!field.isstatic()) continue; if (!field.isAccessible()) { try { field.setAccessible(true); } catch (AccessControlException ex) { continue; } } nametoField.put(field.getName(),field); } staticFields.put(type,nametoField); return nametoField; }
/** * Gets {@code nestedGenericType} annotation from object. * <p> * Looks at all object methods and returns first encountered annotation. * * @param object Object to deal with,not null * @return Annotation,may be null */ public static nestedGenericType getnestedGenericTypeAnnotation(Object object) { nestedGenericType result = null; Method[] methods = ClassReflection.getmethods(object.getClass()); // Todo - use type annotation,not method? for (Method m : methods) { Annotation[] annotations = m.getDeclaredAnnotations(); Annotation a = m.getDeclaredAnnotation(nestedGenericType.class); if (a != null) { result = a.getAnnotation(nestedGenericType.class); break; } } return result; }
/** * Converts json string into java object. * * @param wantedType Wanted type * @param genericTypeKeeper Object with wanted type inside generic argument * @param jsonString Json string data * @param <R> Return type * @return */ public static <R> R process(Class<?> wantedType,Object genericTypeKeeper,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)) { nestedGenericType nestedGenericType = AnnotationProcessor.getnestedGenericTypeAnnotation(genericTypeKeeper); if (nestedGenericType == null) throw new nestedGenericTypeAnnotationMissingException(); json.setDefaultSerializer(new JsonListMapDeserializer(wantedType,nestedGenericType.value())); result = (R) json.fromJson(wantedType,jsonString); } else { result = (R) json.fromJson(wantedType,jsonString); } return result; }
/** * 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() throws PlatformdistributorException { 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) { e.printstacktrace(); throw new PlatformdistributorException("Something wrong with environment"); } }
private Bundlable get() { try { String clName = getString( CLASS_NAME ); if (aliases.containsKey( clName )) { clName = aliases.get( clName ); } Class<?> cl = ClassReflection.forName( clName ); if (cl != null) { Bundlable object = (Bundlable) ClassReflection.newInstance(cl); object.restoreFromBundle( this ); return object; } else { return null; } } catch (Exception e) { e = null; return null; } }
public void invoke(JGameObject clickTarget) { for (Component component : clickTarget.getAllComponents()) { if (component.getClass().getName().equals(invokeComponent)) { Object[] parameters = args.toArray(new Object[args.size()]); Class[] parametersType = new Class[args.size()]; for (int x = 0; x < parameters.length; x++) { parametersType[x] = parameters[x].getClass(); } try { Method method = ClassReflection.getDeclaredMethod(component.getClass(),invokeMethod,parametersType); method.invoke(component,parameters); } catch (ReflectionException e) { e.printstacktrace(); } } } }
@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?"); } }
@Override public void read(Json json,JsonValue jsonData) { try { colors = json.readValue("colors",Array.class,jsonData); fonts = json.readValue("fonts",jsonData); classstyleMap = new OrderedMap<>(); for (JsonValue data : jsonData.get("classstyleMap").iterator()) { classstyleMap.put(ClassReflection.forName(data.name),json.readValue(Array.class,data)); } for (Array<StyleData> styleDatas : classstyleMap.values()) { for (StyleData styleData : styleDatas) { styleData.jsonData = this; } } customClasses = json.readValue("customClasses",CustomClass.class,new Array<>(),jsonData); for (CustomClass customClass : customClasses) { customClass.setMain(main); } } catch (ReflectionException e) { Gdx.app.log(getClass().getName(),"Error parsing json data during file read",e); main.getDialogFactory().showDialogError("Error while reading file...","Error while attempting to read save file.\nPlease ensure that file is not corrupted.\n\nopen error log?"); } }
/** 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); } } } }
/** 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); } }
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; }
/** * Read the actions from the suppled XML element and loads them into the * supplied ActionsContainer. * * The XML element should contain children in the following format: * * <pre> * <actionClassName parameter1Name="parameter1Value" parameter2Name="parameter2Value" ... /> * </pre> * * @param ac * @param actionsElement */ @SuppressWarnings({ "unchecked" }) public static void readActions(ActionsContainer ac,Element actionsElement) { if (actionsElement != null) { for (int i = 0; i < actionsElement.getChildCount(); ++i) { Element actionElement = actionsElement.getChild(i); String implementationClassName = actionElement.getName(); implementationClassName = Action.class.getPackage().getName() + "." + StringUtil.capitalizefirstLetter(implementationClassName); try { Class<? extends Action> actionClass = (Class<? extends Action>) ClassReflection .forName(implementationClassName); Action newAction = ac.addAction(actionClass); if (newAction != null) { newAction.loadFromXML(actionElement); } } catch (ReflectionException e) { throw new GdxRuntimeException(e); } } } }
/** Loads the given SCML stream pointing to a file saved at the given path. * * @param stream the SCML stream * @param scmlFile the path to the SCML file */ public static void load (InputStream stream,String scmlFile) { SCMLReader reader = new SCMLReader(stream); Data data = reader.data; loadedData.put(scmlFile,data); loaderDependencies[0] = data; try { Loader loader = (Loader)ClassReflection.getDeclaredConstructor(loaderClass,loaderTypes).newInstance(loaderDependencies); loader.load(RavTech.files.getAssetHandle(scmlFile)); loaders.add(loader); for (Entity entity : data.entities) entityToLoader.put(entity,loader); } catch (Exception e) { e.printstacktrace(); } }
private void tryLoadDesktopTwitteraPI() { if (Gdx.app.getType() != ApplicationType.Desktop) { Gdx.app.debug(TAG,"Skip loading Twitter API for Desktop. Not running Desktop. \n"); return; } try { final Class<?> twitterClazz = ClassReflection.forName("de.tomgrill.gdxtwitter.desktop.DesktopTwitteraPI"); Object twitter = ClassReflection.getConstructor(twitterClazz,TwitterConfig.class).newInstance(config); twitteraPI = (TwitteraPI) twitter; Gdx.app.debug(TAG,"gdx-twitter for Desktop loaded successfully."); } catch (ReflectionException e) { Gdx.app.debug(TAG,"Error creating gdx-twitter for Desktop (are the gdx-twitter **.jar files installed?). \n"); e.printstacktrace(); } }
private void tryLoadHTMLTwitteraPI() { if (Gdx.app.getType() != ApplicationType.WebGL) { Gdx.app.debug(TAG,"Skip loading gdx-twitter for HTML. Not running HTML. \n"); return; } try { final Class<?> twitterClazz = ClassReflection.forName("de.tomgrill.gdxtwitter.html.HTMLTwitteraPI"); Object twitter = ClassReflection.getConstructor(twitterClazz,"gdx-twitter for HTML loaded successfully."); } catch (ReflectionException e) { Gdx.app.debug(TAG,"Error creating gdx-twitter for HTML (are the gdx-twitter **.jar files installed?). \n"); e.printstacktrace(); } }
private void tryLoadioSTWitteraPI() { if (Gdx.app.getType() != ApplicationType.iOS) { Gdx.app.debug(TAG,"Skip loading gdx-twitter for iOS. Not running iOS. \n"); return; } try { // Class<?> activityClazz = // ClassReflection.forName("com.badlogic.gdx.backends.iosrobovm.IOSApplication"); final Class<?> twitterClazz = ClassReflection.forName("de.tomgrill.gdxtwitter.ios.IOSTwitteraPI"); Object twitter = ClassReflection.getConstructor(twitterClazz,TwitterConfig.class).newInstance(config); twitteraPI = (TwitteraPI) twitter; Gdx.app.debug(TAG,"gdx-twitter for iOS loaded successfully."); } catch (ReflectionException e) { Gdx.app.debug(TAG,"Error creating gdx-twitter for iOS (are the gdx-twitter **.jar files installed?). \n"); e.printstacktrace(); } }
@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); }
@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); }
@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); }
public static AbstractOnDeathEffect load(Element xml) { Class<AbstractOnDeathEffect> c = ClassMap.get(xml.getName().toupperCase()); AbstractOnDeathEffect type = null; try { type = (AbstractOnDeathEffect)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractFieldInteractionType load(Element xml) { Class<AbstractFieldInteractionType> c = ClassMap.get(xml.getName().toupperCase()); AbstractFieldInteractionType type = null; try { type = (AbstractFieldInteractionType)ClassReflection.newInstance(c); } catch (Exception e) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractSpreadStyle load(Element xml) { Class<AbstractSpreadStyle> c = ClassMap.get(xml.getName().toupperCase()); AbstractSpreadStyle type = null; try { type = (AbstractSpreadStyle)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractDurationStyle load(Element xml) { Class<AbstractDurationStyle> c = ClassMap.get(xml.getName().toupperCase()); AbstractDurationStyle type = null; try { type = (AbstractDurationStyle)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractOnTurnEffect load( Element xml ) { Class<AbstractOnTurnEffect> c = ClassMap.get( xml.getName().toupperCase() ); AbstractOnTurnEffect type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractQuestInput load( XmlReader.Element xml ) { Class<AbstractQuestInput> c = ClassMap.get( xml.getName().toupperCase() ); AbstractQuestInput type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractQuestOutputCondition load( XmlReader.Element xml ) { Class<AbstractQuestOutputCondition> c = ClassMap.get( xml.getName().toupperCase() ); AbstractQuestOutputCondition type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractSpriteAnimation load( Element xml ) { Class<AbstractSpriteAnimation> c = ClassMap.get( xml.getName().toupperCase() ); AbstractSpriteAnimation type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
@Override public void parse( Element xmlElement ) { Element xml = xmlElement.getChild( 0 ); try { Class<BehavIoUrTreeNode> c = ClassMap.get( xml.getName().toupperCase() ); BehavIoUrTreeNode node = ClassReflection.newInstance( c ); setNode( node ); node.parse( xml ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } }
@Override public void parse( Element xmlElement ) { for ( int i = 0; i < xmlElement.getChildCount(); i++ ) { Element xml = xmlElement.getChild( i ); try { Class<BehavIoUrTreeNode> c = ClassMap.get( xml.getName().toupperCase() ); BehavIoUrTreeNode node = ClassReflection.newInstance( c ); addNode( node ); node.parse( xml ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } } }
public static AbstractActivationAction load( XmlReader.Element xml ) { Class<AbstractActivationAction> c = ClassMap.get( xml.getName().toupperCase() ); AbstractActivationAction type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractActivationCondition load( XmlReader.Element xml ) { Class<AbstractActivationCondition> c = ClassMap.get( xml.getName().toupperCase() ); AbstractActivationCondition type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractOnDeathEvent load( Element xml ) { Class<AbstractOnDeathEvent> c = ClassMap.get( xml.getName().toupperCase() ); AbstractOnDeathEvent type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractOnHitEvent load( XmlReader.Element xml ) { Class<AbstractOnHitEvent> c = ClassMap.get( xml.getName().toupperCase() ); AbstractOnHitEvent type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
public static AbstractOnTaskEvent load( Element xml ) { Class<AbstractOnTaskEvent> c = ClassMap.get( xml.getName().toupperCase() ); AbstractOnTaskEvent type = null; try { type = ClassReflection.newInstance( c ); } catch ( Exception e ) { System.err.println(xml.getName()); e.printstacktrace(); } type.parse( xml ); return type; }
com.badlogic.gdx.utils.reflect.ReflectionException的实例源码
@Override public Object read(ByteBuffer byteBuffer) { try { byte id = byteBuffer.get(); if(id == -2){ return FrameworkSerializer.read(byteBuffer); }else { Class<?> type = Registrator.getByID(id); Packet packet = (Packet) ClassReflection.newInstance(type); packet.read(byteBuffer); return packet; } }catch (ReflectionException e){ throw new RuntimeException(e); } }
/** * Returns the Class matching the name of the JsonValue,or null if there is no match or it's nameless. */ private Class getClass(JsonValue value,ObjectMap<String,Class> tagsToClasses) { if (value.name() != null && value.name().length() > 0) { String className = value.name(); Class type = tagsToClasses.get(className); if (type == null) { try { type = ClassReflection.forName(className); } catch (ReflectionException ex) { type = null; } } return type; } return null; }
/** * 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() throws PlatformdistributorException { 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) { e.printstacktrace(); throw new PlatformdistributorException("Something wrong with environment"); } }
public void invoke(JGameObject clickTarget) { for (Component component : clickTarget.getAllComponents()) { if (component.getClass().getName().equals(invokeComponent)) { Object[] parameters = args.toArray(new Object[args.size()]); Class[] parametersType = new Class[args.size()]; for (int x = 0; x < parameters.length; x++) { parametersType[x] = parameters[x].getClass(); } try { Method method = ClassReflection.getDeclaredMethod(component.getClass(),invokeMethod,parametersType); method.invoke(component,parameters); } catch (ReflectionException e) { e.printstacktrace(); } } } }
@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?"); } }
@Override public void read(Json json,JsonValue jsonData) { try { colors = json.readValue("colors",Array.class,jsonData); fonts = json.readValue("fonts",jsonData); classstyleMap = new OrderedMap<>(); for (JsonValue data : jsonData.get("classstyleMap").iterator()) { classstyleMap.put(ClassReflection.forName(data.name),json.readValue(Array.class,data)); } for (Array<StyleData> styleDatas : classstyleMap.values()) { for (StyleData styleData : styleDatas) { styleData.jsonData = this; } } customClasses = json.readValue("customClasses",CustomClass.class,new Array<>(),jsonData); for (CustomClass customClass : customClasses) { customClass.setMain(main); } } catch (ReflectionException e) { Gdx.app.log(getClass().getName(),"Error parsing json data during file read",e); main.getDialogFactory().showDialogError("Error while reading file...","Error while attempting to read save file.\nPlease ensure that file is not corrupted.\n\nopen error log?"); } }
/** 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); } }
/** * Read the actions from the suppled XML element and loads them into the * supplied ActionsContainer. * * The XML element should contain children in the following format: * * <pre> * <actionClassName parameter1Name="parameter1Value" parameter2Name="parameter2Value" ... /> * </pre> * * @param ac * @param actionsElement */ @SuppressWarnings({ "unchecked" }) public static void readActions(ActionsContainer ac,Element actionsElement) { if (actionsElement != null) { for (int i = 0; i < actionsElement.getChildCount(); ++i) { Element actionElement = actionsElement.getChild(i); String implementationClassName = actionElement.getName(); implementationClassName = Action.class.getPackage().getName() + "." + StringUtil.capitalizefirstLetter(implementationClassName); try { Class<? extends Action> actionClass = (Class<? extends Action>) ClassReflection .forName(implementationClassName); Action newAction = ac.addAction(actionClass); if (newAction != null) { newAction.loadFromXML(actionElement); } } catch (ReflectionException e) { throw new GdxRuntimeException(e); } } } }
@Test @SuppressWarnings("static-access") public void androidisLoadedWithV4Fragment() { androidSetup(); Mockito.when(classReflectionMock.isAssignableFrom(activityStub.getClass(),Gdx.app.getClass())).thenReturn(false); Mockito.when(classReflectionMock.isAssignableFrom(supportFragmentStub.getClass(),Gdx.app.getClass())).thenReturn(true); try { Mockito.when(constructorMock.newInstance(activityStub,config)).thenReturn(twitteraPIStub); Mockito.when(classReflectionMock.forName("android.support.v4.app.Fragment")).thenReturn(supportFragmentStub.getClass()); Mockito.when(classReflectionMock.getmethod(supportFragmentStub.getClass(),"getActivity")).thenReturn(methodMock); Mockito.when(methodMock.invoke(Gdx.app)).thenReturn(activityStub); } catch (ReflectionException e) { } fixture = new TwitterSystem(config); assertEquals(twitteraPIStub,fixture.getTwitteraPI()); }
@Test @SuppressWarnings("static-access") public void androidisLoadedWithFragment() { androidSetup(); Mockito.when(classReflectionMock.isAssignableFrom(activityStub.getClass(),Gdx.app.getClass())).thenReturn(false); Mockito.when(classReflectionMock.isAssignableFrom(fragmentStub.getClass(),config)).thenReturn(twitteraPIStub); Mockito.when(classReflectionMock.forName("android.app.Fragment")).thenReturn(fragmentStub.getClass()); Mockito.when(classReflectionMock.getmethod(fragmentStub.getClass(),"getActivity")).thenReturn(methodMock); Mockito.when(methodMock.invoke(Gdx.app)).thenReturn(activityStub); } catch (ReflectionException e) { } fixture = new TwitterSystem(config); assertEquals(twitteraPIStub,fixture.getTwitteraPI()); }
private void tryLoadHTMLTwitteraPI() { if (Gdx.app.getType() != ApplicationType.WebGL) { Gdx.app.debug(TAG,"Skip loading gdx-twitter for HTML. Not running HTML. \n"); return; } try { final Class<?> twitterClazz = ClassReflection.forName("de.tomgrill.gdxtwitter.html.HTMLTwitteraPI"); Object twitter = ClassReflection.getConstructor(twitterClazz,TwitterConfig.class).newInstance(config); twitteraPI = (TwitteraPI) twitter; Gdx.app.debug(TAG,"gdx-twitter for HTML loaded successfully."); } catch (ReflectionException e) { Gdx.app.debug(TAG,"Error creating gdx-twitter for HTML (are the gdx-twitter **.jar files installed?). \n"); e.printstacktrace(); } }
private void tryLoadioSTWitteraPI() { if (Gdx.app.getType() != ApplicationType.iOS) { Gdx.app.debug(TAG,"Skip loading gdx-twitter for iOS. Not running iOS. \n"); return; } try { // Class<?> activityClazz = // ClassReflection.forName("com.badlogic.gdx.backends.iosrobovm.IOSApplication"); final Class<?> twitterClazz = ClassReflection.forName("de.tomgrill.gdxtwitter.ios.IOSTwitteraPI"); Object twitter = ClassReflection.getConstructor(twitterClazz,TwitterConfig.class).newInstance(config); twitteraPI = (TwitteraPI) twitter; Gdx.app.debug(TAG,"gdx-twitter for iOS loaded successfully."); } catch (ReflectionException e) { Gdx.app.debug(TAG,"Error creating gdx-twitter for iOS (are the gdx-twitter **.jar files installed?). \n"); e.printstacktrace(); } }
private void handleLazyAssetInjection(final Object component,final Field field,final Asset assetData) { if (Annotations.isNotVoid(assetData.lazyCollection())) { handleLazyAssetCollectionInjection(component,field,assetData); return; } else if (assetData.value().length != 1) { throw new GdxRuntimeException( "Lazy wrapper can contain only one asset if lazy collection type is not provided. Found multiple assets in field: " + field + " of component: " + component); } final String assetPath = assetData.value()[0]; if (!assetData.loadondemand()) { load(assetPath,assetData.type()); } try { Reflection.setFieldValue(field,component,Lazy.providedBy(new AssetProvider(this,assetPath,assetData.type(),assetData.loadondemand()))); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject lazy asset.",exception); } }
@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); }
@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); }
@SuppressWarnings({ "rawtypes","unchecked" }) private void injectAssets(final AssetService assetService) { try { ObjectMap map = (ObjectMap) Reflection.getFieldValue(field,component); if (map == null) { map = GdxMaps.newObjectMap(); } for (int assetIndex = 0; assetIndex < assetPaths.length; assetIndex++) { map.put(assetKeys[assetIndex],assetService.get(assetPaths[assetIndex],assetType)); } Reflection.setFieldValue(field,map); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject map of assets into component: " + component + ".",exception); } }
public static AbstractOnDeathEffect load(Element xml) { Class<AbstractOnDeathEffect> c = ClassMap.get(xml.getName().toupperCase()); AbstractOnDeathEffect type = null; try { type = (AbstractOnDeathEffect)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractSpreadStyle load(Element xml) { Class<AbstractSpreadStyle> c = ClassMap.get(xml.getName().toupperCase()); AbstractSpreadStyle type = null; try { type = (AbstractSpreadStyle)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractDurationStyle load(Element xml) { Class<AbstractDurationStyle> c = ClassMap.get(xml.getName().toupperCase()); AbstractDurationStyle type = null; try { type = (AbstractDurationStyle)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractTownEvent load(XmlReader.Element xml ) { Class<AbstractTownEvent> c = ClassMap.get(xml.getName().toupperCase()); AbstractTownEvent type = null; try { type = (AbstractTownEvent) ClassReflection.newInstance( c ); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractHitType load(XmlReader.Element xml ) { Class<AbstractHitType> c = ClassMap.get(xml.getName().toupperCase()); AbstractHitType type = null; try { type = (AbstractHitType) ClassReflection.newInstance( c ); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstracttargetingType load(Element xml) { Class<AbstracttargetingType> c = ClassMap.get(xml.getName().toupperCase()); AbstracttargetingType type = null; try { type = (AbstracttargetingType)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
public static AbstractCostType load(Element xml) { Class<AbstractCostType> c = ClassMap.get(xml.getName().toupperCase()); AbstractCostType type = null; try { type = (AbstractCostType)ClassReflection.newInstance(c); } catch (ReflectionException e) { e.printstacktrace(); } type.parse(xml); return type; }
private static void processClassName(final Iterable<Class<? extends Annotation>> annotations,final Array<Class<?>> result,final String packageName,final String className) { if (!className.startsWith(packageName)) { return; } try { final Class<?> classtoProcess = ClassReflection.forName(className); for (final Class<? extends Annotation> annotation : annotations) { if (ClassReflection.isAnnotationPresent(classtoProcess,annotation)) { result.add(classtoProcess); return; } } } catch (final ReflectionException exception) { exception.printstacktrace(); // Unexpected. Classes should be present. } }
@SuppressWarnings({ "rawtypes","unchecked" }) private void injectAssets(final AssetService assetService) { try { ObjectSet set = (ObjectSet) Reflection.getFieldValue(field,component); if (set == null) { set = GdxSets.newSet(); } for (final String assetPath : assetPaths) { set.add(assetService.get(assetPath,set); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject set of assets into component: " + component + ".",exception); } }
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(); } }
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(); } }
private static Array<Class<?>> extractFromBinaries(final Iterable<Class<? extends Annotation>> annotations,final String mainPackageName,final Queue<Pair<File,Integer>> filesWithDepthsToProcess) throws ReflectionException { final Array<Class<?>> result = GdxArrays.newArray(); while (!filesWithDepthsToProcess.isEmpty()) { final Pair<File,Integer> classpathFileWithDepth = filesWithDepthsToProcess.poll(); final File classpathFile = classpathFileWithDepth.getFirst(); final int depth = classpathFileWithDepth.getSecond(); if (classpathFile.isDirectory()) { addAllChildren(filesWithDepthsToProcess,classpathFile,depth); } else { final String className = getBinaryClassName(mainPackageName,depth); if (!isFromPackage(mainPackageName,className)) { continue; } final Class<?> classtoProcess = ClassReflection.forName(className); processClass(annotations,result,classtoProcess); } } return result; }
@Override public void processField(final Field field,final LmlMacro annotation,final Object component,final Context context,final Contextinitializer initializer,final ContextDestroyer contextDestroyer) { try { final Object macroData = Reflection.getFieldValue(field,component); final LmlParser parser = interfaceService.get().getParser(); final FileType fileType = annotation.fileType(); if (macroData instanceof String) { parser.parseTemplate(Gdx.files.getFileHandle((String) macroData,fileType)); } else if (macroData instanceof String[]) { for (final String macroPath : (String[]) macroData) { parser.parseTemplate(Gdx.files.getFileHandle(macroPath,fileType)); } } else { throw new GdxRuntimeException("Invalid type of LML macro deFinition in component: " + component + ". String or String[] expected,received: " + macroData + "."); } } catch (final ReflectionException exception) { throw new GdxRuntimeException( "Unable to extract macro paths from field: " + field + " of component: " + component + ".",exception); } }
/** Invoked when all skins are loaded. Injects skin assets. * * @param interfaceService used to retrieve skins. * @return {@link OnMessage#REMOVE}. */ @SuppressWarnings("unchecked") @OnMessage(AutumnMessage.SKINS_LOADED) public boolean injectFields(final InterfaceService interfaceService) { for (final Entry<Pair<String,String>,Array<Pair<Field,Object>>> entry : fieldsToInject) { final Skin skin = interfaceService.getParser().getData().getSkin(entry.key.getSecond()); final String assetId = entry.key.getFirst(); if (skin == null) { throw new ContextinitiationException( "Unable to inject asset: " + assetId + ". UnkNown skin ID: " + entry.key.getSecond()); } for (final Pair<Field,Object> injection : entry.value) { try { Reflection.setFieldValue(injection.getFirst(),injection.getSecond(),skin.get(assetId,injection.getFirst().getType())); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject skin asset: " + assetId + " from skin: " + skin + " to field: " + injection.getFirst() + " of component: " + injection.getSecond(),exception); } } } fieldsToInject.clear(); return OnMessage.REMOVE; }
@Override public void processField(final Field field,final LmlParserSyntax annotation,final ContextDestroyer contextDestroyer) { try { final Object Syntax = Reflection.getFieldValue(field,component); if (Syntax instanceof LmlSyntax) { interfaceService.getParser().setSyntax((LmlSyntax) Syntax); } else { throw new ContextinitiationException( "LmlParserSyntax-annotated fields need to contain an instance of LmlSyntax. Found: " + Syntax + " in field: " + field + " of component: " + component); } } catch (final ReflectionException exception) { throw new ContextinitiationException( "Unable to extract LML Syntax from field: " + field + " of component: " + component,exception); } }
@SuppressWarnings({ "rawtypes",exception); } }
@SuppressWarnings({ "rawtypes","unchecked" }) private void injectAssets(final AssetService assetService) { try { Array array = (Array) Reflection.getFieldValue(field,component); if (array == null) { array = GdxArrays.newArray(); } for (final String assetPath : assetPaths) { array.add(assetService.get(assetPath,array); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject array of assets into component: " + component + ".",exception); } }
private void handleLazyAssetInjection(final Object component,exception); } }
private void handleRegularassetInjection(final Object component,final Asset assetData) { if (assetData.value().length != 1) { throw new GdxRuntimeException( "Regular fields can store only 1 asset. If the field is a collection,its type is not currently supported: only LibGDX Array,ObjectSet and ObjectMap are permitted. Regular arrays will not be supported. Found multiple assets in field: " + field + " of component: " + component); } final String assetPath = assetData.value()[0]; if (assetData.loadondemand()) { // Loaded immediately. @SuppressWarnings("unchecked") final Object asset = finishLoading(assetPath,field.getType()); try { Reflection.setFieldValue(field,asset); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject asset loaded on demand.",exception); } } else { load(assetPath,field.getType()); // Scheduled to be loaded,delayed injection. assetInjections.add(new StandardAssetInjection(field,component)); } }
@SuppressWarnings({ "rawtypes","unchecked" }) private void handleMapInjection(final Object component,final Asset assetData) { if (assetData.loadondemand()) { final String[] assetPaths = assetData.value(); final String[] assetKeys = assetData.keys().length == 0 ? assetData.value() : assetData.keys(); try { ObjectMap assets = (ObjectMap) Reflection.getFieldValue(field,component); if (assets == null) { assets = GdxMaps.newObjectMap(); } for (int assetIndex = 0; assetIndex < assetPaths.length; assetIndex++) { assets.put(assetKeys[assetIndex],finishLoading(assetPaths[assetIndex],assetData.type())); } Reflection.setFieldValue(field,assets); } catch (final ReflectionException exception) { throw new GdxRuntimeException("Unable to inject array of assets into: " + component,exception); } } else { for (final String assetPath : assetData.value()) { load(assetPath,assetData.type()); } // Scheduled to be loaded,delayed injection. assetInjections.add(new ObjectMapAssetInjection(assetData.value(),assetData.keys(),component)); } }
@Override public void processField(final Field field,final AvailableLocales annotation,final ContextDestroyer contextDestroyer) { try { final Object locales = Reflection.getFieldValue(field,component); if (locales instanceof String[]) { final String[] availableLocales = (String[]) locales; final LmlParser parser = interfaceService.getParser(); parser.getData().addArgument(annotation.viewArgumentName(),availableLocales); for (final String locale : availableLocales) { parser.getData().addActorConsumer(annotation.localeChangeMethodPrefix() + locale,new LocaleChangingAction(localeService,LocaleService.toLocale(locale))); } return; } throw new GdxRuntimeException("Invalid field annotated with @AvailableLocales in component " + component + ". Expected String[],received: " + locales + "."); } catch (final ReflectionException exception) { throw new GdxRuntimeException( "Unable to read available locales from field: " + field + " of component: " + component + ".",exception); } }
protected <View> void processLmlInjectAnnotation(final View view,final Field field) { if (Reflection.isAnnotationPresent(field,LmlInject.class)) { try { final LmlInject injectionData = Reflection.getAnnotation(field,LmlInject.class); final Class<?> injectedValueType = getLmlInjectedValueType(field,injectionData); if (LmlParser.class.equals(injectedValueType)) { // Injected type equals LmlParser - parser injection was requested: Reflection.setFieldValue(field,view,this); return; } Object value = Reflection.getFieldValue(field,view); if (value == null || injectionData.newInstance()) { value = Reflection.newInstance(injectedValueType); Reflection.setFieldValue(field,value); } // Processing field's value annotations: processViewFieldAnnotations(value); } catch (final ReflectionException exception) { throw new GdxRuntimeException( "Unable to inject value of LmlInject-annotated field: " + field + " of view: " + view,exception); } } }
com.google.common.reflect.Reflection的实例源码
private ImmutableList<Method> getVisibleMethods(Class<?> cls) { // Don't use cls.getPackage() because it does nasty things like reading // a file. String visiblePackage = Reflection.getPackageName(cls); ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Class<?> type : Typetoken.of(cls).getTypes().rawTypes()) { if (!Reflection.getPackageName(type).equals(visiblePackage)) { break; } for (Method method : type.getDeclaredMethods()) { if (!method.isSynthetic() && isVisible(method)) { builder.add(method); } } } return builder.build(); }
/** * Tests null checks against the instance methods of the return values,if any. * * <p>Test fails if default value cannot be determined for a constructor or factory method * parameter,or if the constructor or factory method throws exception. * * @return this tester */ public FactoryMethodReturnValueTester testNulls() throws Exception { for (Invokable<?,?> factory : getFactoriesTotest()) { Object instance = instantiate(factory); if (instance != null && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) { try { nullPointerTester.testAllPublicInstanceMethods(instance); } catch (AssertionError e) { AssertionError error = new AssertionFailedError( "Null check Failed on return value of " + factory); error.initCause(e); throw error; } } } return this; }
private static Object getDefaultValue(Class<?> returnType) { Object defaultValue = ArbitraryInstances.get(returnType); if (defaultValue != null) { return defaultValue; } if ("java.util.function.Predicate".equals(returnType.getCanonicalName()) || ("java.util.function.Consumer".equals(returnType.getCanonicalName()))) { // Generally,methods that accept java.util.function.* instances // don't like to get null values. We generate them dynamically // using Proxy so that we can have Java 7 compliant code. return Reflection.newProxy(returnType,new AbstractInvocationHandler() { @Override public Object handleInvocation(Object proxy,Method method,Object[] args) { // Crude,but acceptable until we can use Java 8. Other // methods have default implementations,and it is hard to // distinguish. if ("test".equals(method.getName()) || "accept".equals(method.getName())) { return getDefaultValue(method.getReturnType()); } throw new IllegalStateException("Unexpected " + method + " invoked on " + proxy); } }); } else { return null; } }
private ImmutableList<Method> getVisibleMethods(Class<?> cls) { // Don't use cls.getPackage() because it does nasty things like reading // a file. String visiblePackage = Reflection.getPackageName(cls); ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Class<?> type : Typetoken.of(cls).getTypes().rawTypes()) { if (!Reflection.getPackageName(type).equals(visiblePackage)) { break; } for (Method method : type.getDeclaredMethods()) { if (!method.isSynthetic() && isVisible(method)) { builder.add(method); } } } return builder.build(); }
/** * Tests null checks against the instance methods of the return values,?> factory : getFactoriesTotest()) { Object instance = instantiate(factory); if (instance != null && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) { try { nullPointerTester.testAllPublicInstanceMethods(instance); } catch (AssertionError e) { AssertionError error = new AssertionFailedError( "Null check Failed on return value of " + factory); error.initCause(e); throw error; } } } return this; }
private static Object getDefaultValue(Class<?> returnType) { Object defaultValue = ArbitraryInstances.get(returnType); if (defaultValue != null) { return defaultValue; } if ("java.util.function.Predicate".equals(returnType.getCanonicalName()) || ("java.util.function.Consumer".equals(returnType.getCanonicalName()))) { // Generally,and it is hard to // distinguish. if ("test".equals(method.getName()) || "accept".equals(method.getName())) { return getDefaultValue(method.getReturnType()); } throw new IllegalStateException("Unexpected " + method + " invoked on " + proxy); } }); } else { return null; } }
public void put(final ModuleIdentifier moduleIdentifier,final Module module,final ModuleFactory moduleFactory,final ModuleInternalInfo maybeOldInternalInfo,final TransactionModuleJMXRegistration transactionModuleJMXRegistration,final boolean isDefaultBean,final BundleContext bundleContext) { transactionStatus.checkNotCommitted(); Class<? extends Module> moduleClass = Module.class; if (module instanceof RuntimeBeanRegistratorAwareModule) { moduleClass = RuntimeBeanRegistratorAwareModule.class; } Module proxiedModule = Reflection.newProxy(moduleClass,new ModuleInvocationHandler(deadlockMonitor,moduleIdentifier,module)); ModuleInternalTransactionalInfo moduleInternalTransactionalInfo = new ModuleInternalTransactionalInfo( moduleIdentifier,proxiedModule,moduleFactory,maybeOldInternalInfo,transactionModuleJMXRegistration,isDefaultBean,module,bundleContext); modulesHolder.put(moduleInternalTransactionalInfo); }
@Override public AutoCloseable createInstance() { // The service is provided via blueprint so wait for and return it here for backwards compatibility. final WaitingServiceTracker<Timer> tracker = WaitingServiceTracker.create( Timer.class,bundleContext,"(type=global-timer)"); final Timer timer = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); return Reflection.newProxy(AutoCloseableTimerInterface.class,new AbstractInvocationHandler() { @Override protected Object handleInvocation(final Object proxy,final Method method,final Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { return method.invoke(timer,args); } } }); }
@Override public AutoCloseable createInstance() { // The service is provided via blueprint so wait for and return it here for backwards compatibility. String typeFilter = String.format("(type=%s)",getIdentifier().getInstanceName()); final WaitingServiceTracker<EventLoopGroup> tracker = WaitingServiceTracker.create( EventLoopGroup.class,typeFilter); final EventLoopGroup group = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); return Reflection.newProxy(AutoCloseableEventLoopGroupInterface.class,final Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { return method.invoke(group,args); } } }); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); dataTree = InMemoryDataTreeFactory.getInstance().create(TreeType.CONfigURATION); dataTree.setSchemaContext(SCHEMA_CONTEXT); realModification = dataTree.takeSnapshot().newModification(); proxyModification = Reflection.newProxy(DataTreeModification.class,(proxy,method,args) -> { try { method.invoke(mockModification,args); return method.invoke(realModification,args); } catch (InvocationTargetException e) { throw e.getCause(); } }); pruningDataTreeModification = new PruningDataTreeModification(proxyModification,dataTree,SCHEMA_CONTEXT); }
@Override public AutoCloseable createInstance() { final WaitingServiceTracker<EntityOwnershipService> tracker = WaitingServiceTracker.create( EntityOwnershipService.class,bundleContext); final EntityOwnershipService service = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); return Reflection.newProxy(AutoCloseableEntityOwnershipService.class,new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy,Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { try { return method.invoke(service,args); } catch (InvocationTargetException e) { // https://bugs.opendaylight.org/show_bug.cgi?id=6564 // http://stackoverflow.com/a/10719613/421602 // https://amitstechblog.wordpress.com/2011/07/24/java-proxies-and-undeclaredthrowableexception/ throw e.getCause(); } } } }); }
@Override public AutoCloseable createInstance() { final WaitingServiceTracker<ClusterSingletonServiceProvider> tracker = WaitingServiceTracker .create(ClusterSingletonServiceProvider.class,bundleContext); final ClusterSingletonServiceProvider service = tracker.waitForService(WaitingServiceTracker.FIVE_MINUTES); // Create a proxy to override close to close the ServiceTracker. The actual DOMClusterSingletonServiceProvider // instance will be closed via blueprint. return Reflection.newProxy(AutoCloseableDOMClusterSingletonServiceProvider.class,new AbstractInvocationHandler() { @Override protected Object handleInvocation(final Object proxy,final Object[] args) throws Throwable { if (method.getName().equals("close")) { tracker.close(); return null; } else { return method.invoke(service,args); } } }); }
public static <S> PartitionContextValidator<S> newPartitionContextTest(final Class<S> ifc,final Class<? extends S> impl) { final PartitionContextsupplier supplier = new AnnotationPartitionContextsupplier(ifc,impl); return new PartitionContextValidator<S>() { @Override public S expect(final PartitionContext expected) { return Reflection.newProxy(ifc,new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy,Object[] args) throws Throwable { PartitionContext actual = supplier.forCall(method,args); assertEquals(actual,expected,"Expected=" + expected.asMap() + ",Actual=" + actual.asMap()); return Defaults.defaultValue(method.getReturnType()); } }); } }; }
/** * Create new composite listener for a collection of delegates. */ @SafeVarargs public static <T extends ParseTreeListener> T create(Class<T> type,T... delegates) { ImmutableList<T> listeners = ImmutableList.copyOf(delegates); return Reflection.newProxy(type,new AbstractInvocationHandler() { @Override @ParametersAreNonnullByDefault protected Object handleInvocation(Object proxy,Object[] args) throws Throwable { for (T listener : listeners) { method.invoke(listener,args); } return null; } @Override public String toString() { return MoreObjects.toStringHelper("CompositeParseTreeListener") .add("listeners",listeners) .toString(); } }); }
/** * {@inheritDoc} */ public T getobject() throws Exception { final T mapper = getsqlSession().getMapper(this.mapperInterface); return Reflection.newProxy(this.mapperInterface,new InvocationHandler() { @Override public Object invoke(Object proxy,Object[] args) throws Throwable { long start = System.currentTimeMillis(); TraceContext rpc = TraceContext.get(); String parameters = getParameters(args); String iface = Mapperfactorybean.this.iface; rpc.reset().inc().setStamp(start).setIface(iface).setMethod(method.getName()).setParameter(parameters); try { return method.invoke(mapper,args); } catch (Exception e) { rpc.setFail(true).setReason(e.getMessage()); LOG.error("{}.{}({})",iface,method.getName(),parameters,e); throw e; } finally { rpc.setCost(System.currentTimeMillis() - start); TraceRecorder.getInstance().post(rpc.copy()); } } }); }
private ImmutableList<Method> getVisibleMethods(Class<?> cls) { // Don't use cls.getPackage() because it does nasty things like reading // a file. String visiblePackage = Reflection.getPackageName(cls); ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Class<?> type : Typetoken.of(cls).getTypes().classes().rawTypes()) { if (!Reflection.getPackageName(type).equals(visiblePackage)) { break; } for (Method method : type.getDeclaredMethods()) { if (!method.isSynthetic() && isVisible(method)) { builder.add(method); } } } return builder.build(); }
/** * Tests null checks against the instance methods of the return values,?> factory : getFactoriesTotest()) { Object instance = instantiate(factory); if (instance != null && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) { try { nullPointerTester.testAllPublicInstanceMethods(instance); } catch (AssertionError e) { AssertionError error = new AssertionFailedError( "Null check Failed on return value of " + factory); error.initCause(e); throw error; } } } return this; }
private ImmutableList<Method> getVisibleMethods(Class<?> cls) { // Don't use cls.getPackage() because it does nasty things like reading // a file. String visiblePackage = Reflection.getPackageName(cls); ImmutableList.Builder<Method> builder = ImmutableList.builder(); for (Class<?> type : Typetoken.of(cls).getTypes().rawTypes()) { if (!Reflection.getPackageName(type).equals(visiblePackage)) { break; } for (Method method : type.getDeclaredMethods()) { if (!method.isSynthetic() && isVisible(method)) { builder.add(method); } } } return builder.build(); }
/** * Tests null checks against the instance methods of the return values,?> factory : getFactoriesTotest()) { Object instance = instantiate(factory); if (instance != null && packagesToTest.contains(Reflection.getPackageName(instance.getClass()))) { try { nullPointerTester.testAllPublicInstanceMethods(instance); } catch (AssertionError e) { AssertionError error = new AssertionFailedError("Null check Failed on return value of " + factory); error.initCause(e); throw error; } } } return this; }
/** Makes a fresh type variable that's only equal to itself. */ @SuppressWarnings("unchecked") // Delegates to the <T> of class Var except getName(). static TypeVariable<Class<?>> freshTypeVariable(final String name) { // Use dynamic proxy so we only changes the behavior of getName() and equals/hashCode // Everything else delegates to a JDK native type variable. return Reflection.newProxy(TypeVariable.class,new AbstractInvocationHandler() { @Override protected Object handleInvocation(Object proxy,Object[] args) throws Throwable { if (method.getName().equals("getName")) { return name; } try { return method.invoke(PROTOTYPE,args); } catch (InvocationTargetException e) { throw e.getCause(); } } @Override public String toString() { return name; } }); }
@Override public boolean handle(Field f,Object target,supplier<Fixture<S>> context) { if (f.isAnnotationPresent(org.magenta.annotations.InjectFixture.class)) { InjectFixture annotation = f.getAnnotation(org.magenta.annotations.InjectFixture.class); if (Fixture.class.equals(f.getType())) { Fixture proxy = Reflection.newProxy(Fixture.class,handler(context)); FieldInjectorUtils.injectInto(target,f,proxy); return true; } else { throw new IllegalStateException("Annotation " + InjectFixture.class.getName() + " is present on field named " + f.getName() + ",but this field type is not a " + Fixture.class.getName()); } } else { return false; } }
/** Transforms the given {@code UniformVisitor} into a {@code CsstreeVisitor}. */ public static CsstreeVisitor asVisitor(final UniformVisitor visitor) { return Reflection.newProxy( CsstreeVisitor.class,new InvocationHandler() { @Override public Object invoke(Object proxy,Object[] args) throws Throwable { // Allow methods from Object,like toString(). if (Object.class.equals(method.getDeclaringClass())) { return method.invoke(visitor,args); } CssNode node = (CssNode) args[0]; if (method.getName().startsWith("enter")) { visitor.enter(node); return true; // Always visit children } else if (method.getName().startsWith("leave")) { visitor.leave(node); return null; // All leave* methods are void } throw new IllegalStateException("Unexpected method '" + method + "' called"); } }); }
/** * Transforms the given visitor into a {@code CsstreeVisitor} that calls the {@code * UniformVisitor}'s {@code enter} method before each {@code enter*} method and its {@code * leave} method after each {@code leave*} method. */ public static <T extends UniformVisitor & CsstreeVisitor> CsstreeVisitor asCombinedVisitor( final T visitor) { return Reflection.newProxy( CsstreeVisitor.class,args); } CssNode node = (CssNode) args[0]; if (method.getName().startsWith("enter")) { visitor.enter(node); return method.invoke(visitor,args); } else if (method.getName().startsWith("leave")) { Object result = method.invoke(visitor,args); visitor.leave(node); return result; } throw new IllegalStateException("Unexpected method '" + method + "' called"); } }); }
@SuppressWarnings({"unchecked","rawtypes"}) public static BeanManager beanManager(final CompletableFuture<Registry> injector) { return Reflection.newProxy(BeanManager.class,args) -> { final String name = method.getName(); switch (name) { case "createAnnotatedType": return createAnnotatedType((Class) args[0]); case "createInjectionTarget": return createInjectionTarget(injector,((AnnotatedType) args[0]).getJavaClass()); case "createCreationalContext": return createCreationalContext(); case "toString": return injector.toString(); default: throw new UnsupportedOperationException(method.toString()); } }); }
@SuppressWarnings("unchecked") private static <T> InjectionTarget<T> createInjectionTarget( final CompletableFuture<Registry> injector,final Class<T> type) { return Reflection.newProxy(InjectionTarget.class,args) -> { final String name = method.getName(); switch (name) { case "produce": return injector.get().require(type); case "inject": return null; case "postconstruct": return null; case "preDestroy": return null; case "dispose": return null; default: throw new UnsupportedOperationException(method.toString()); } }); }
@SuppressWarnings("rawtypes") private static Injector proxyInjector(final ClassLoader loader,final Map<Key,Object> registry) { return Reflection.newProxy(Injector.class,args) -> { if (method.getName().equals("getInstance")) { Key key = (Key) args[0]; Object value = registry.get(key); if (value == null) { Object type = key.getAnnotation() != null ? key : key.getTypeLiteral(); IllegalStateException iex = new IllegalStateException("Not found: " + type); // Skip proxy and some useless lines: Try.apply(() -> { StackTraceElement[] stacktrace = iex.getStackTrace(); return Lists.newArrayList(stacktrace).subList(CLEAN_STACK,stacktrace.length); }).onSuccess(stacktrace -> iex .setStackTrace(stacktrace.toArray(new StackTraceElement[stacktrace.size()]))); throw iex; } return value; } throw new UnsupportedOperationException(method.toString()); }); }
public void universalPreInit(FMLPreInitializationEvent event) { Configuration config = new Configuration(event.getSuggestedConfigurationFile()); packets = Network.newChannel("SevenCommons") .register(PacketSync.class,SYNC_PACKET_ID) .register(PacketInventoryName.class) .register(PacketContainerButton.class) .build(); ClassInfoUtil.preInit(); // initialize the lazy statics in the scheduler class Reflection.initialize(Scheduler.class); TickRegistry.registerTickHandler(new SCPlayerTicker(),Side.SERVER); GameRegistry.registerPlayerTracker(new SCPlayerTracker()); proxy.preInit(event); Syncing.registerFactory(Object.class,new BuiltinSyncers()); ToNbtFactories.registerFactory(Object.class,new DefaultNBTSerializers()); }
/** * <p>Define a new Class specified by the given bytes.</p> * * @param bytes the bytes describing the class * @param context the class which to use as the context * @return the defined class */ public static Class<?> defineDynamicclass(byte[] bytes,Class<?> context) { if (DEBUG) { try { ClassNode node = ASMUtils.getThinClassNode(bytes); File file = new File("sevencommonsdyn/" + node.name + ".class"); Files.createParentDirs(file); OutputStream out = new FileOutputStream(file); out.write(bytes); out.close(); } catch (IOException e) { e.printstacktrace(); } } ClassLoader cl = context.getClassLoader(); Class<?> clazz; try { clazz = (Class<?>) CLASS_LOADER_DEFINE.invokeExact(cl,(String) null,bytes,bytes.length); } catch (Throwable t) { throw Throwables.propagate(t); } Reflection.initialize(clazz); return clazz; }
@SneakyThrows protected void configure() { // 初始化 Provider SourceProviderManager provider = instance(SourceProviderManager.class); // 包扫描所有已经实现的Provider ImmutableSet<Class<SourceProvider>> plugins = new PluginLoader<>(SourceProvider.class,Reflection .getPackageName(SourceProvider.class),ClassLoader.getSystemClassLoader()) .getPlugins(); for (Class<SourceProvider> clazz : Iterables.filter(plugins,annotatedBy(Enabled.class))) { provider.addProvider(instance(clazz)); } // 绑定 Service DefaultCollectionService service = new DefaultCollectionService(provider); bind(CollectionService.class).toInstance(service); }
/** * Decide whether this RateLimiter extension is applicable to the original service / utility * object. If so,wrap it in a proxy object with rate-limit-aware invocation handle; if not,just * return the original object. */ private <T> T getProxyObject( T originalObject,AdWordsSession session,Class<T> cls,boolean isUtility) { // Find the retry strategy of this class type. ApiRetryStrategy retryStrategy = ApiRetryStrategyManager.getRetryStrategy(cls.getSimpleName(),isUtility); // If no corresponding retry strategy,just use the original object instead of a wrapping proxy. if (retryStrategy == null) { return originalObject; } InvocationHandler invocationHandler = new ApiInvocationHandlerWithRateLimiter(originalObject,session,retryStrategy); return Reflection.newProxy(cls,invocationHandler); }
/** * * @param strUrl 连接字符串 * @param interfaceClass 接口类 * @return */ private static Object createStandardProxy(Class<?> interfaceclass,String serviceName,Class<?> implMethod,LoadBalance balance) { InvocationHandler handler = new ProxyStandard(interfaceclass,serviceName,implMethod,balance); // Object obj = Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),new Class[] { interfaceclass },handler); Object obj = Reflection.newProxy(interfaceclass,handler); logger.info(String.format("create jdkproxy for %s ",interfaceclass.getName())); return obj; }
private FactoryMethodReturnValueTester( Class<?> declaringClass,ImmutableList<Invokable<?,?>> factories,String factoryMethodsDescription) { this.declaringClass = declaringClass; this.factories = factories; this.factoryMethodsDescription = factoryMethodsDescription; packagesToTest.add(Reflection.getPackageName(declaringClass)); }
private FactoryMethodReturnValueTester( Class<?> declaringClass,String factoryMethodsDescription) { this.declaringClass = declaringClass; this.factories = factories; this.factoryMethodsDescription = factoryMethodsDescription; packagesToTest.add(Reflection.getPackageName(declaringClass)); }
private static AutoCloseableEventExecutor createCloseableProxy( final CloseableEventExecutorMixin closeableEventExecutorMixin) { return Reflection.newProxy(AutoCloseableEventExecutor.class,final Object[] args) throws Throwable { if (method.getName().equals("close")) { closeableEventExecutorMixin.close(); return null; } else { return method.invoke(closeableEventExecutorMixin.eventExecutor,args); } } }); }
private S createDelegate(ServiceEndPoint endPoint) { final S delegateService = _delegate.create(endPoint); S proxiedService = Reflection.newProxy(_serviceClass,Object[] args) throws Throwable { try { return method.invoke(delegateService,args); } catch (InvocationTargetException e) { // If the target exception is a declared exception then rethrow as-is Throwable targetException = e.getTargetException(); for (Class<?> declaredException : method.getExceptionTypes()) { // noinspection unchecked Throwables.propagateIfInstanceOf(targetException,(Class<? extends Throwable>) declaredException); } // If the exception was due to connection issues and not necessarily the target let the caller kNow. // It's possible the connection timed out due to a problem on the target,but from our perspective // there's no definitive way of kNowing. if (targetException instanceof ClientHandlerException) { _errorMeter.mark(); throw new PartitionForwardingException("Failed to handle request at endpoint",targetException.getCause()); } throw Throwables.propagate(targetException); } } }); _proxiedToDelegateServices.put(proxiedService,delegateService); return proxiedService; }
@Test public void testShouldBeScanned() throws Exception { CoreConfigurationNonRestartable config = new CoreConfigurationNonRestartable(); config.scannedPrefixes.add(Reflection.getPackageName(getClass()).replace('.','/')); assertTrue(config.shouldClassPathResourceBeScanned(getClass().getName().replace('.','/') + ".class")); assertFalse(config.shouldClassPathResourceBeScanned("org/eclipse/Test")); }
public void testExceptionBecomesError() throws Exception { // Ensure that if the annotation processor code gets an unexpected exception,it is converted // into a compiler error rather than being propagated. Otherwise the output can be very // confusing to the user who stumbles into a bug that causes an exception,whether in // AutoparseProcessor or javac. // We inject an exception by rigging fileManager to throw when the processor tries to output // the generated class for an otherwise correct @Autoparse class. final AtomicBoolean exceptionWasThrown = new AtomicBoolean(); final String message = "I don't understand the question,and I won't respond to it"; final StandardJavaFileManager realFileManager = fileManager; InvocationHandler errorInjectionHandler = new InvocationHandler() { @Override public Object invoke(Object proxy,Object[] args) throws Throwable { if (method.getName().equals("getJavaFileForOutput")) { exceptionWasThrown.set(true); throw new UnsupportedOperationException(message); } else { return method.invoke(realFileManager,args); } } }; fileManager = Reflection.newProxy(StandardJavaFileManager.class,errorInjectionHandler); String testSourceCode = "package foo.bar;\n" + "import auto.parse.Autoparse;\n" + "@Autoparse\n" + "public abstract class Empty {\n" + "}\n"; assertCompilationResultIs( ImmutableMultimap.of(Diagnostic.Kind.ERROR,Pattern.compile(message,Pattern.LIteraL)),ImmutableList.of(testSourceCode)); assertTrue(exceptionWasThrown.get()); }
private FactoryMethodReturnValueTester( Class<?> declaringClass,String factoryMethodsDescription) { this.declaringClass = declaringClass; this.factories = factories; this.factoryMethodsDescription = factoryMethodsDescription; packagesToTest.add(Reflection.getPackageName(declaringClass)); }
今天的关于Java Reflection-对象不是声明类的实例和java有哪些不是对象的数据的分享已经结束,谢谢您的关注,如果想了解更多关于com.badlogic.gdx.utils.reflect.ArrayReflection的实例源码、com.badlogic.gdx.utils.reflect.ClassReflection的实例源码、com.badlogic.gdx.utils.reflect.ReflectionException的实例源码、com.google.common.reflect.Reflection的实例源码的相关知识,请在本站进行查询。
本文标签: