@SuppressWarnings({"unchecked"}) public T createInstance(String managerClassName) { Class managerClass = ReflectionUtil.loadClass(managerClassName); if (managerClass == null) { logger.warn("Cannot load class: {}", managerClassName); managerClass = defaultImplClass; } if (!clazz.isAssignableFrom(managerClass)) { logger.warn("Cannot use as {}: {}", clazz.getName(), managerClassName); managerClass = defaultImplClass; } logger.debug("Using class: {}", managerClass.getName()); T instance = (T) ReflectionUtil.newInstance(managerClass); if (instance == null) { logger.warn( "Cannot instanciate: {}. Fall back to default: {}.", managerClass.getName(), FieldsManager.class.getName()); instance = (T) ReflectionUtil.newInstance(defaultImplClass); if (instance == null) { logger.error("Cannot instanciate: {}", defaultImplClass.getName()); } } logger.debug("Installed {0}: {1}", clazz.getName(), instance); return instance; }
@Test public void testNewInstance() { String foo = ReflectionUtil.newInstance(String.class); assertNotNull(foo); Foo1 foo1 = ReflectionUtil.newInstance(Foo1.class); assertNotNull(foo1); Foo2 foo2 = ReflectionUtil.newInstance(Foo2.class); assertNotNull(foo2); Foo3 foo3 = ReflectionUtil.newInstance(Foo3.class); assertNotNull(foo3); class FooConverter implements Converter<FooConverter, ConverterInvocation> { @Override public FooConverter convert(ConverterInvocation input) { return this; } } FooConverter foo4 = ReflectionUtil.newInstance(FooConverter.class); assertNotNull(foo4); }
static { try { PACKET_PLAY_OUT_ENTITY_STATUS = ReflectionUtil.getNMSClass("PacketPlayOutEntityStatus") .getConstructor(ReflectionUtil.getNMSClass("Entity"), byte.class); } catch (Exception e) { e.printStackTrace(); } }
public class PlayerUtil { private static final Method sendPacket = ReflectionUtil.getMethod( ReflectionUtil.getNMSClass("PlayerConnection"), ReflectionConstants.PLAYER_FUNC_SENDPACKET.getName(), ReflectionUtil.getNMSClass("Packet")); public static void sendPacket(Player player, Object packet) { Object playerConnection = getPlayerConnection(player); try { sendPacket.invoke(playerConnection, packet); } catch (IllegalAccessException e) { EchoPet.getPlugin() .getReflectionLogger() .warning("Failed to retrieve the PlayerConnection of: " + player.getName()); } catch (IllegalArgumentException e) { EchoPet.getPlugin() .getReflectionLogger() .warning("Failed to retrieve the PlayerConnection of: " + player.getName()); } catch (InvocationTargetException e) { EchoPet.getPlugin() .getReflectionLogger() .warning("Failed to retrieve the PlayerConnection of: " + player.getName()); } } public static Object playerToEntityPlayer(Player player) { Method getHandle = ReflectionUtil.getMethod(player.getClass(), "getHandle"); try { return getHandle.invoke(player); } catch (IllegalAccessException e) { EchoPet.getPlugin() .getReflectionLogger() .warning("Failed retrieve the NMS Player-Object of:" + player.getName()); return null; } catch (IllegalArgumentException e) { EchoPet.getPlugin() .getReflectionLogger() .warning("Failed retrieve the NMS Player-Object of:" + player.getName()); return null; } catch (InvocationTargetException e) { EchoPet.getPlugin() .getReflectionLogger() .warning("Failed retrieve the NMS Player-Object of:" + player.getName()); return null; } } public static Object getPlayerConnection(Player player) { return ReflectionUtil.getField( ReflectionUtil.getNMSClass("EntityPlayer"), ReflectionConstants.PLAYER_FIELD_CONNECTION.getName(), playerToEntityPlayer(player)); } }
public JSONMessage achievementTooltip(final Achievement which) { try { Object achievement = ReflectionUtil.getMethod(obcStatistic, "getNMSAchievement").invoke(null, which); return achievementTooltip( (String) ReflectionUtil.getField(nmsAchievement, "name").get(achievement)); } catch (Exception e) { e.printStackTrace(); return this; } }
/** invokes the given Runnable */ public void invoke(boolean wait, Runnable r) { if (r == null) { return; } if (NativeWindowFactory.isAWTAvailable()) { initAWTReflection(); // handover to AWT MainThread .. try { if (((Boolean) ReflectionUtil.callMethod(null, mAWTIsDispatchThread, null)) .booleanValue()) { r.run(); return; } if (wait) { ReflectionUtil.callMethod(null, mAWTInvokeAndWait, new Object[] {r}); } else { ReflectionUtil.callMethod(null, mAWTInvokeLater, new Object[] {r}); } } catch (Exception e) { throw new NativeWindowException(e); } return; } // if this main thread is not being used or // if this is already the main thread .. just execute. if (!isRunning() || mainThread == Thread.currentThread()) { r.run(); return; } boolean doWait = wait && isRunning() && mainThread != Thread.currentThread(); Object lock = new Object(); RunnableTask rTask = new RunnableTask(r, doWait ? lock : null, true); Throwable throwable = null; synchronized (lock) { invokeLater(rTask); if (doWait) { try { lock.wait(); } catch (InterruptedException ie) { throwable = ie; } } } if (null == throwable) { throwable = rTask.getThrowable(); } if (null != throwable) { throw new RuntimeException(throwable); } }
public void sendToLocation(Packet63WorldParticles packet, Location l) throws Exception { ReflectionUtil.setValue(packet, "a", particleName); ReflectionUtil.setValue(packet, "b", (float) l.getX()); ReflectionUtil.setValue(packet, "c", (float) l.getY()); ReflectionUtil.setValue(packet, "d", (float) l.getZ()); ReflectionUtil.setValue(packet, "e", new Random().nextFloat()); ReflectionUtil.setValue(packet, "f", new Random().nextFloat()); ReflectionUtil.setValue(packet, "g", new Random().nextFloat()); ReflectionUtil.setValue(packet, "h", defaultSpeed); ReflectionUtil.setValue(packet, "i", particleAmount); ReflectionUtil.sendPacketToLocation(l, packet); }
public JSONMessage itemTooltip(final ItemStack itemStack) { try { Object nmsItem = ReflectionUtil.getMethod(obcItemStack, "asNMSCopy", ItemStack.class) .invoke(null, itemStack); return itemTooltip( ReflectionUtil.getMethod(nmsItemStack, "save") .invoke(nmsItem, nmsTagCompound.newInstance()) .toString()); } catch (Exception e) { e.printStackTrace(); return this; } }
private void initAWTReflection() { if (null == cAWTEventQueue) { ClassLoader cl = MainThread.class.getClassLoader(); cAWTEventQueue = ReflectionUtil.getClass("java.awt.EventQueue", true, cl); mAWTInvokeAndWait = ReflectionUtil.getMethod( cAWTEventQueue, "invokeAndWait", new Class[] {java.lang.Runnable.class}, cl); mAWTInvokeLater = ReflectionUtil.getMethod( cAWTEventQueue, "invokeLater", new Class[] {java.lang.Runnable.class}, cl); mAWTIsDispatchThread = ReflectionUtil.getMethod(cAWTEventQueue, "isDispatchThread", new Class[] {}, cl); } }
public <T extends Model<K>, K> void exportToCsv( String fileName, BaseDao<T, K> dao, String[] fields) { try { Files.createDirectories(Paths.get(DIR)); StringBuilder content = new StringBuilder(); DBCursor<T> iterable = dao.find(); for (T t : iterable) { for (String fieldName : fields) { Method getter = ReflectionUtil.getGetter(t.getClass(), fieldName); try { String value = String.valueOf(getter.invoke(t)); content.append(value).append(','); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } content.append('\n'); } Files.write( Paths.get(DIR + fileName), content.toString().getBytes("UTF-8"), CREATE, WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { e.printStackTrace(); } }
// obj: "object with properties" to write private void writeObject(Object obj) throws NoSuchMethodException, InstantiationException, InvocationTargetException, IllegalAccessException, SecurityException { // begin bean encoding: this.driver.startElement(DTD.ELEMENT_OBJECT); Class cls = obj.getClass(); final String mappedName = this.context.aliasFor(cls); this.driver.setAttribute( DTD.ATTRIBUTE_CLASS, (mappedName != null ? mappedName : cls.getName())); // encode properties: while (cls != Object.class) { // process inheritance: for (Field f : cls.getDeclaredFields()) { // process composition: if (Modifier.isStatic(f.getModifiers()) || !ReflectionUtil.hasClassFieldProperty(cls, f) || this.context.excluded(f)) { continue; // skip static or non-property or excluded field. } // get property field: if (!f.isAccessible()) { f.setAccessible(true); } // write property value: final String aliasedFieldName = this.context.aliasFor(f, f.getName()); this.driver.startElement(aliasedFieldName); this.write0(f.get(obj)); this.driver.endElement(); } cls = cls.getSuperclass(); } // end bean encoding: this.driver.endElement(); }
@SuppressWarnings("unchecked") // protected by 'if (type.isAssignableFrom(clazz)) {' public final void loadClassesFromMap(final Map<?, ?> properties, final Class<O> type) { final ClassLoader loader = ReflectionUtil.getClassLoader(); for (Entry<?, ?> entry : properties.entrySet()) { final String className = entry.getValue().toString(); final String name = entry.getKey().toString(); try { final Class<?> clazz = loader.loadClass(className); if (type.isAssignableFrom(clazz)) { registerClass(name, (Class<? extends O>) clazz); } else { throw new MetafactureException( className + " does not implement " + type.getName() + " registration with " + this.getClass().getSimpleName() + " failed."); } } catch (ClassNotFoundException e) { throw new MetafactureException(className + " not found", e); } } }
public JSONMessage statisticTooltip(final Statistic which) { Type type = which.getType(); if (type != Type.UNTYPED) { throw new IllegalArgumentException( "That statistic requires an additional " + type + " parameter!"); } try { Object statistic = ReflectionUtil.getMethod(obcStatistic, "getNMSStatistic").invoke(null, which); return achievementTooltip( (String) ReflectionUtil.getField(nmsStatistic, "name").get(statistic)); } catch (Exception e) { e.printStackTrace(); return this; } }
@Override public <T> T defaultInstanceFor(Class<T> c) throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { final Object cached = cachedDefCtors.get(c); if (cached != null) { if (cached.getClass() == Constructor.class) { return ((Constructor<T>) cached).newInstance(); } if (cached.getClass() == NoSuchMethodException.class) { throw (NoSuchMethodException) cached; } if (cached.getClass() == InstantiationException.class) { throw (InstantiationException) cached; } if (cached.getClass() == InvocationTargetException.class) { throw (InvocationTargetException) cached; } if (cached.getClass() == IllegalAccessException.class) { throw (IllegalAccessException) cached; } } try { final Constructor<T> ctor = ReflectionUtil.defaultConstructor(c); T ret = ctor.newInstance(); cachedDefCtors.putIfAbsent(c, ctor); return ret; } catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException noDefCtorX) { cachedDefCtors.putIfAbsent(c, noDefCtorX); throw noDefCtorX; } }
public void executeEvent(MethodSpecifier eventMethodSpecifier, Scope scope) { Set<Method> beforeMethods = eventMethodSpecifier.getMethods(scope); for (Method beforeMethod : beforeMethods) { ReflectionUtil.invokeWithArgs( beforeMethod, addAndGetComponent(beforeMethod.getDeclaringClass())); } }
public <T> void exportToCsv(String fileName, Iterator<T> data) { try { Files.createDirectories(Paths.get(DIR)); StringBuilder content = new StringBuilder(); List<Method> getters = null; while (data.hasNext()) { T t = data.next(); if (getters == null) { getters = ReflectionUtil.getAllGetters(t.getClass()); getters.sort((a, b) -> a.getName().length() - b.getName().length()); } for (Method getter : getters) { try { String value = String.valueOf(getter.invoke(t)); content.append(value).append(','); } catch (IllegalAccessException | InvocationTargetException e) { e.printStackTrace(); } } content.append('\n'); } Files.write( Paths.get(DIR + fileName), content.toString().getBytes("UTF-8"), CREATE, WRITE, StandardOpenOption.TRUNCATE_EXISTING); } catch (IOException e) { e.printStackTrace(); } }
public boolean isCurrentThreadEDT() { if (NativeWindowFactory.isAWTAvailable()) { initAWTReflection(); return ((Boolean) ReflectionUtil.callMethod(null, mAWTIsDispatchThread, null)).booleanValue(); } return isRunning() && mainThread == Thread.currentThread(); }
public DataWatcher() { try { datawatcher = ReflectionUtil.getNMSClass("DataWatcher"); } catch (Exception e) { e.printStackTrace(); } }
public ObjectWrapper getWrapper(String classname) { ObjectWrapper ret; Class type = ReflectionUtil.classForName(transfer2classname(classname)); if (type == null) return null; else { return getWrapper(type); } }
public void send(Player player) { try { Object handle = ReflectionUtil.getHandle(player); Object connection = ReflectionUtil.getField(handle.getClass(), "playerConnection").get(handle); Object serialized = ReflectionUtil.getMethod(nmsChatSerializer, "a", String.class) .invoke(null, toJSONString()); Object packet = nmsPacketPlayOutChat .getConstructor(ReflectionUtil.getNMSClass("IChatBaseComponent")) .newInstance(serialized); ReflectionUtil.getMethod(connection.getClass(), "sendPacket").invoke(connection, packet); } catch (Exception e) { e.printStackTrace(); } }
@Test public void testSetFieldValueForId() { TestRecord record = new TestRecord(); record.setName("Bla bla"); ReflectionUtil.setFieldValueForId(record, 1L); Assert.assertEquals(1L, record.getId().longValue()); }
@GwtIncompatible("java.lang.reflect.Field") public HasField hasField(final String fieldName) { final T subject = getSubject(); if (subject == null) { failureStrategy.fail("Cannot determine a field name from a null object."); // Needed for Expect and other non-terminal failure strategies return new HasField() { @Override public void withValue(Object value) { Subject.this.fail("Cannot test the presence of a value in a null object."); } }; } final Class<?> subjectClass = subject.getClass(); final Field field; try { field = ReflectionUtil.getField(subjectClass, fieldName); field.setAccessible(true); } catch (NoSuchFieldException e) { StringBuilder message = new StringBuilder("Not true that "); message.append("<").append(subjectClass.getSimpleName()).append(">"); message.append(" has a field named <").append(fieldName).append(">"); failureStrategy.fail(message.toString()); // Needed for Expect and other non-terminal failure strategies return new HasField() { @Override public void withValue(Object value) { Subject.this.fail("Cannot test the presence of a value in a non-present field."); } }; } return new HasField() { @Override public void withValue(Object expected) { try { Object actual = field.get(subject); if (expected == actual || (expected != null && expected.equals(actual))) { return; } else { StringBuilder message = new StringBuilder("Not true that "); message.append("<").append(subjectClass.getSimpleName()).append(">'s"); message.append(" field <").append(fieldName).append(">"); message.append(" contains expected value <").append(expected).append(">."); message.append(" It contains value <").append(actual).append(">"); failureStrategy.fail(message.toString()); } } catch (IllegalArgumentException e) { throw new RuntimeException( "Error checking field " + fieldName + " while testing for value " + expected); } catch (IllegalAccessException e) { throw new RuntimeException( "Cannot access field " + fieldName + " to test for value " + expected); } } }; }
/** * Play a firework effect at a location * * @param location Location to play firework effect at * @param fireworkEffect FireworkEffect to play */ public static void playToLocation(Location location, FireworkEffect fireworkEffect) { for (Entity entity : location.getWorld().getEntities()) { if (entity instanceof Player) { if (entity.getLocation().distanceSquared(location) <= 60 * 60) { ReflectionUtil.sendPacket((Player) entity, makePacket(location, fireworkEffect)); } } } }
public JSONMessage statisticTooltip(final Statistic which, EntityType entity) { Type type = which.getType(); if (type == Type.UNTYPED) { throw new IllegalArgumentException("That statistic needs no additional parameter!"); } if (type != Type.ENTITY) { throw new IllegalArgumentException( "Wrong parameter type for that statistic - needs " + type + "!"); } try { Object statistic = ReflectionUtil.getMethod(obcStatistic, "getEntityStatistic").invoke(null, which, entity); return achievementTooltip( (String) ReflectionUtil.getField(nmsStatistic, "name").get(statistic)); } catch (Exception e) { e.printStackTrace(); return this; } }
Object invokeMethod(Object objectToInvoke) { Method method = getNaturalLanguageMethod().getMethod(); List<ArgumentConverter> argumentConverters = naturalLanguageMethod.getArgumentConverters(); Object[] args = new Object[matcher.groupCount()]; for (int i = 0; i < matcher.groupCount(); i++) { String group = matcher.group(i + 1); args[i] = argumentConverters.get(i).convertArgument(group, naturalLanguageMethod, i); } return ReflectionUtil.invokeWithArgs(method, objectToInvoke, args); }
public void sendToPlayer(Location l, Player p) throws Exception { Object packet = Class.forName( "net.minecraft.server." + ReflectionUtil.getVersionString() + ".Packet63WorldParticles") .getConstructors()[0] .newInstance(); ReflectionUtil.setValue(packet, "a", particleName); ReflectionUtil.setValue(packet, "b", (float) l.getX()); ReflectionUtil.setValue(packet, "c", (float) l.getY()); ReflectionUtil.setValue(packet, "d", (float) l.getZ()); ReflectionUtil.setValue(packet, "e", new Random().nextFloat()); ReflectionUtil.setValue(packet, "f", new Random().nextFloat()); ReflectionUtil.setValue(packet, "g", new Random().nextFloat()); ReflectionUtil.setValue(packet, "h", defaultSpeed); ReflectionUtil.setValue(packet, "i", particleAmount); ((CraftPlayer) p).getHandle().playerConnection.sendPacket((Packet) packet); }
public static Schema getAsSchema(File schemaFile) { SchemaFactory sm = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); try { Schema schema = sm.newSchema(schemaFile); return schema; } catch (Exception e) { NeptusLog.pub().warn(ReflectionUtil.getCallerStamp() + e.getMessage()); return null; } }
public void addAssociatedEntitiesForAJob( String pipelineName, String stageName, String jobName, Resources resources, ArtifactPlans artifactPlans, ArtifactPropertiesGenerators artifactPropertiesGenerators) { CruiseConfig config = loadForEdit(); JobConfig jobConfig = config .pipelineConfigByName(new CaseInsensitiveString(pipelineName)) .findBy(new CaseInsensitiveString(stageName)) .jobConfigByConfigName(new CaseInsensitiveString(jobName)); ReflectionUtil.setField(jobConfig, "resources", resources); ReflectionUtil.setField(jobConfig, "artifactPlans", artifactPlans); ReflectionUtil.setField( jobConfig, "artifactPropertiesGenerators", artifactPropertiesGenerators); writeConfigFile(config); }
@Test public void testGetTableFields() { List<Field> fieldList = ReflectionUtil.getTableFields(TestRecord.class); List<String> strings = new ArrayList<>(); for (Field field : fieldList) { strings.add(field.getName()); } Assert.assertEquals(true, strings.contains("id")); Assert.assertEquals(true, strings.contains("name")); }
/** 鑾峰緱鍗曞疄渚嬫帴鍙� */ public static MultiCard getInstance(Context context) { if (instance == null) { instance = new MultiCard(); instance.setInternalSDCard(ReflectionUtil.getInternalSDCardPath(context)); instance.mExternalSDCardPath = Environment.getExternalStorageDirectory().getAbsolutePath(); // Util.cjxLog("澶栫疆SD鍗¤矾寰勶細", instance.mExternalSDCardPath); // instance.mPhoneDataPath = Environment.getDataDirectory().getAbsolutePath(); //娌℃潈闄� instance.mPhoneDataPath = context.getFilesDir().getAbsolutePath(); // Util.cjxLog("鎵嬫満DATA璺緞锛�, instance.mPhoneDataPath); } instance.makeAllDirectory(); return instance; }