This is just a piece of what I am working at the moment I want to use currentTimeMillis() to print the time for an image to be loaded any reasons why it does not work?
package method;
import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;
public class TracingInvocationHandler implements InvocationHandler {
private Object target;
private PrintWriter out;
public TracingInvocationHandler(Object target, PrintWriter out) {
this.target = target;
this.out = out;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
long startTime = System.currentTimeMillis();
Object result = null;
out.println("Image " + method.getName() + " (...) entered.");
result = method.invoke(target, args);
out.println("Image " + method.getName() + " (...) returned.");
long endTime = System.currentTimeMillis();
System.out.printf(" [%s] %s Image %s took %d ms:",new Date().toString(), method.getName(),args[0], (endTime - startTime) + "ms");
return result;
}
public static Object createProxy(Object target, PrintWriter out) {
Class<?> targetClass = target.getClass();
ClassLoader currentClassLoader = targetClass.getClassLoader();
Class<?>[] interfaces = targetClass.getInterfaces();
InvocationHandler handler = new TracingInvocationHandler(target, out);
return Proxy.newProxyInstance(currentClassLoader, interfaces, handler);
}
Remove + "ms"
from (endTime - startTime) + "ms"
. The corresponding format %d
in the pattern expects a numeric object. (endTime - startTime) + "ms"
produces a String
.
You probably were receiving an exception. Next time you ask a question, please include it. This time you were lucky.
It's because you are casting a long primitive to float, I recommend you to use a variable where you cast: for example:
long totalTime = endTime - startTime;
String strTotalTime = String.valueOf(totalTime);
System.out.printf(" [%s] %s Image %s took %s ms:",
new Date().toString(), method.getName(), args[0], strTotalTime);
Its invoked but I don't see you pass it to sysout, thats why its not visible. That is you're doing:
long endTime = System.currentTimeMillis();
System.out.printf(" [%s] %s Image %s took %d ms:",new Date().toString(),
instead of:
long endTime = System.currentTimeMillis();
System.out.printf(" [%s] %s Image %s took %d ms:",new Date(endTime).toString(),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.