Update examples

This commit is contained in:
Thibaud Gasser 2019-12-29 12:02:00 +01:00
parent c4477aca38
commit ecdd16363a
5 changed files with 75 additions and 26 deletions

View File

@ -31,7 +31,7 @@ public class Main {
return String.format("Object %s", o); return String.format("Object %s", o);
} }
private static long[] runNTimes(int numberOfRuns, Object[] toTest, Consumer<? super Object> code) { private static <T> long[] runNTimes(int numberOfRuns, T[] toTest, Consumer<T> code) {
long runs[] = new long[numberOfRuns]; long runs[] = new long[numberOfRuns];
for (int i = 0; i < numberOfRuns; i++) { for (int i = 0; i < numberOfRuns; i++) {
long startTime = System.nanoTime(); long startTime = System.nanoTime();
@ -52,7 +52,7 @@ public class Main {
.orWhen(Byte.class::isInstance, b -> "byte " + b) .orWhen(Byte.class::isInstance, b -> "byte " + b)
.orWhen(Double.class::isInstance, d -> "double " + d) .orWhen(Double.class::isInstance, d -> "double " + d)
.orWhen(String.class::isInstance, s -> "String " + s) .orWhen(String.class::isInstance, s -> "String " + s)
.otherwise(o -> "Object " + o); .otherwise(o -> String.format("Object %s", o));
final int nRuns = 100000; final int nRuns = 100000;
final Statistics formatObjectStats = Statistics.from(runNTimes(nRuns, toTest, Main::formatObject)); final Statistics formatObjectStats = Statistics.from(runNTimes(nRuns, toTest, Main::formatObject));

View File

@ -0,0 +1,33 @@
package fr.gasser.daoexample.dao.xml;
import fr.gasser.daoexample.dao.Dao;
import fr.gasser.daoexample.model.Student;
import java.util.List;
public class StudentXmlDao implements Dao<Student> {
@Override
public boolean create(Student obj) {
return false;
}
@Override
public Student find(int id) {
return null;
}
@Override
public List<Student> findAll() {
return null;
}
@Override
public boolean update(Student obj) {
return false;
}
@Override
public boolean delete(Student obj) {
return false;
}
}

View File

@ -4,6 +4,7 @@ import javax.tools.JavaCompiler;
import javax.tools.ToolProvider; import javax.tools.ToolProvider;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.net.URL; import java.net.URL;
import java.net.URLClassLoader; import java.net.URLClassLoader;
@ -12,13 +13,12 @@ import java.nio.file.Files;
import java.util.Arrays; import java.util.Arrays;
public class DynamicLoadDemo { public class DynamicLoadDemo {
/** /**
* The source code to load dynamically * The source code to load dynamically
*/ */
private static final String SOURCE = private static final String SOURCE =
"package test;" "package test;"
+ "import static DynamicLoadDemo.*;" + "import static fr.gasser.reflection.DynamicLoadDemo.*;"
+ "public class Test implements IDynamicLoad {" + "public class Test implements IDynamicLoad {"
+ " static { System.out.println(\"Test\"); }" + " static { System.out.println(\"Test\"); }"
+ " @Override public String doSomething() {" + " @Override public String doSomething() {"
@ -28,7 +28,7 @@ public class DynamicLoadDemo {
+ " return \"Hello reflection! \" + arg;" + " return \"Hello reflection! \" + arg;"
+ " }" + " }"
+ "}"; + "}";
/** /**
* Represents the contract for the dynamically loaded class * Represents the contract for the dynamically loaded class
*/ */
@ -42,32 +42,36 @@ public class DynamicLoadDemo {
* @throws java.lang.ReflectiveOperationException * @throws java.lang.ReflectiveOperationException
*/ */
public static void main(String[] args) throws IOException, ReflectiveOperationException { public static void main(String[] args) throws IOException, ReflectiveOperationException {
// Save source in .java file. // Save source in .java file.
final File root = Files.createTempDirectory(null).toFile(); final File root = Files.createTempDirectory(null).toFile();
final File sourceFile = new File(root, "test/Test.java"); final File sourceFile = new File(root, "test/Test.java");
sourceFile.getParentFile().mkdirs(); if (!sourceFile.getParentFile().mkdirs()) {
System.err.format("Cannot create %s%n", sourceFile.getCanonicalPath());
}
Files.write(sourceFile.toPath(), SOURCE.getBytes(StandardCharsets.UTF_8)); Files.write(sourceFile.toPath(), SOURCE.getBytes(StandardCharsets.UTF_8));
// Compile source file. // Compile source file.
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
compiler.run(null, null, null, sourceFile.getPath()); compiler.run(null, null, null, sourceFile.getPath());
// Load and instantiate compiled class. // Load and instantiate compiled class.
final URLClassLoader classLoader = final URLClassLoader classLoader =
URLClassLoader.newInstance(new URL[] { root.toURI().toURL() }); URLClassLoader.newInstance(new URL[]{ root.toURI().toURL() });
final Class<?> cls = Class.forName("test.Test", true, classLoader); final Class<? extends IDynamicLoad> cls = Class.forName("test.Test", true, classLoader)
IDynamicLoad instance = (IDynamicLoad) cls.newInstance(); .asSubclass(IDynamicLoad.class);
final Constructor<? extends IDynamicLoad> ctor = cls.getConstructor();
IDynamicLoad instance = ctor.newInstance();
System.out.format( System.out.format(
"Methods declared by the class : %s%n", "Methods declared by the class : %s%n",
Arrays.toString(cls.getDeclaredMethods()) Arrays.toString(cls.getDeclaredMethods())
); );
// Invoke methods of the contract IDynamicLoad // Invoke methods of the contract IDynamicLoad
System.out.println(instance.doSomething()); System.out.println(instance.doSomething());
// Invoke methods using the reflection API // Invoke methods using the reflection API
Method method = cls.getDeclaredMethod("doSomethingReflection", String.class); Method method = cls.getDeclaredMethod("doSomethingReflection", String.class);
System.out.format("invoking %s.doSomethingReflection()%n", cls.getName()); System.out.format("invoking %s.doSomethingReflection()%n", cls.getName());
System.out.println(method.invoke(instance, "With an argument")); System.out.println(method.invoke(instance, "With an argument"));
} }

View File

@ -1,14 +1,16 @@
package fr.gasser.reflection; package fr.gasser.reflection;
import java.util.List;
public class GenericsTest<T> { public class GenericsTest<T> {
private TypeToken<T> typeToken; private TypeToken<?> typeToken;
private T data; private T data;
public GenericsTest(T data) { public GenericsTest(T data, TypeToken<?> typeToken) {
this.data = data; this.data = data;
this.typeToken = new TypeToken<T>() {}; this.typeToken = typeToken;
} }
@Override @Override
@ -20,7 +22,8 @@ public class GenericsTest<T> {
} }
public static void main(String[] args) { public static void main(String[] args) {
GenericsTest<Long> g = new GenericsTest<>(5L); List<Long> longs = List.of(5L);
GenericsTest<List<Long>> g = new GenericsTest<>(longs, new TypeToken<List<Long>>(){});
System.out.println(g); System.out.println(g);
} }
} }

View File

@ -3,7 +3,7 @@ package fr.gasser.reflection;
import java.lang.reflect.*; import java.lang.reflect.*;
import java.util.List; import java.util.List;
/* /**
* {@code TypeToken<List<String>> list = new TypeToken<List<String>>() {};} * {@code TypeToken<List<String>> list = new TypeToken<List<String>>() {};}
*/ */
public class TypeToken<T> { public class TypeToken<T> {
@ -70,8 +70,9 @@ public class TypeToken<T> {
} else { } else {
String className = type == null ? "null" : type.getClass().getName(); String className = type == null ? "null" : type.getClass().getName();
throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " throw new IllegalArgumentException(String.format(
+ "GenericArrayType, but <" + type + "> is of type " + className); "Expected a Class, ParameterizedType, or GenericArrayType, but <%s> is of type %s", type, className
));
} }
} }
@ -92,7 +93,15 @@ public class TypeToken<T> {
* Gets type literal for the given {@code Class} instance. * Gets type literal for the given {@code Class} instance.
*/ */
public static <T> TypeToken<T> get(Class<T> type) { public static <T> TypeToken<T> get(Class<T> type) {
return new TypeToken<T>(type); return new TypeToken<>(type);
}
@Override
public String toString() {
return "TypeToken{" +
"rawType=" + rawType +
", type=" + type +
'}';
} }
public static void main(String[] args) { public static void main(String[] args) {