C++ dot vs arrow
http://www.tutorialspoint.com/cplusplus/cpp_member_operators.htm
C++ pointer vs reference
http://www.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReference.html
http://stackoverflow.com/questions/114180/pointer-vs-reference
http://stackoverflow.com/questions/57483/what-are-the-differences-between-
pointer-variable-and-reference-variable-in-c
如何在Linux下跑UI测试,但是不打扰你的工作/Run UI tests in the background on Linux
一句话,起点vncserver,使用vncviewer连上去,跑你自己的UI测试就可以了。
如何编译opencv
1. 从opencv的官网下载source,然后编译,安装;
2. 编写你的opencv code
3. 使用以下命令来编译:
g++ -I/YouIncludePath/usr/include -L/YouLibPath/usr/lib64 -lopencv_calib3d
-lopencv_contrib -lopencv_core -lopencv_features2d -lopencv_flann -lopencv_gpu
-lopencv_highgui -lopencv_imgproc -lopencv_legacy -lopencv_ml -lopencv_nonfree
-lopencv_objdetect -lopencv_photo -lopencv_stitching -lopencv_superres
-lopencv_ts -lopencv_video -lopencv_videostab YouTest.cpp
在opencv中,如何获得contour所包围的范围内的值
如果你想使用opencv区分边界的话,可以使用findContours,但是在确认边界后,
你又想知道边界里面或者外面是什么,你可以使用pointPolygonTest方法来判断。
如下例子:
cv::Point2f findPointInContour(cv::Rect& rect, std::vector< cv::Point > contour)
{
cv::Point2f onTheEdge1;
int where = 0;
for (int i = rect.x; i < rect.x + rect.width; i++) {
for (int j = rect.y; j < rect.y + rect.height; j++) {
where = (int) (cv::pointPolygonTest(contour, cv::Point2f(i, j), false));
//cout << "x = " << i << " y = " << j << "distance " << where << endl;
if (where > 0) { //inside
return cv::Point2f(i, j);
} else if (where == 0) { //on the edge
onTheEdge1 = cv::Point2f(i, j);
}
}
}
return onTheEdge1;
}
opencv中的findContours的使用
1. findContours对0包围1的情况,会找出1来。
例如:
0,0,0
0,1,0
0,0,0 找出来的contour是1,1.
2. findContours对1包围0的情况,会找出0周围的点来。
1,1,1
1,0,1
1,1,1 找出来的contour是1,0;2,1;1,2;0,1
3. findContours会将传入的矩阵中的非零值设置成1,零值设置成0,找出相应的contour。
4. 以下是一个打印处所有contour的例子:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv/cv.h"
#include <iostream>
using namespace std;
using namespace cv;
void printContours(Mat & mat, Mat& copy);
int main(char* args) {
int length = 15;
int border3 = 3;
int border1 = 1;
Mat mat1(length, length, CV_8UC1, Scalar::all(1));
Mat mat2(length, length, CV_8UC1, Scalar::all(0));
Mat mat3(length, length, CV_8UC1, Scalar::all(1));
mat2.at< unsigned char >(2,2) = 0;
cout << "mat2 = "<< endl << " " << mat2 << endl << endl;
Mat copy = mat2.clone();
printContours(mat2, copy);
}
void printContours(Mat & mat, Mat& copy) {
/// Find contours
vector<vector<Point> > contours;
vector<Vec4i> hierarchy;
findContours( mat, contours, hierarchy, RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
int contourSize = contours.size();
for(int i = 0; i < contourSize; i++) {
cout << "contours = "<< endl << " " << contours[i] << endl << endl;
Rect rect = cv::boundingRect(contours[i]);
cout << "rect = "<< endl << " " << rect << endl << endl;
double area = cv::contourArea(contours[i], true);
cout << "area = "<< endl << " " << area << endl << endl;
}
int hierarchySize = hierarchy.size();
for(int i = 0; i < hierarchySize; i ++) {
cout << "hierarchy = "<< endl << " " << hierarchy[i] << endl << endl;
}
cout << "mat = "<< endl << " " << mat << endl << endl;
}
创建opencv Matrix时候的type
opencv matrix type:
CV_[The number of bits per item][Signed or Unsigned][Type Prefix]C[The channel
number]
CV_
M1 with one channel =
[255, 255;
255, 255]
M2 with two channel =
[0, 255, 0, 255;
0, 255, 0, 255]
M3 with three channel =
[0, 0, 255, 0, 0, 255;
0, 0, 255, 0, 0, 255]
#include "opencv/cv.h"
#include <iostream>
using namespace std;
using namespace cv;
int main(char* args) {
Mat M1(2,2, CV_8UC1, 255);
Mat M2(2,2, CV_8UC2, Scalar(0,255));
Mat M3(2,2, CV_8UC3, Scalar(0,0,255));
cout << "M1 with one channel = "<< endl << " " << M1 << endl << endl;
cout << "M2 with two channel = "<< endl << " " << M2 << endl << endl;
cout << "M3 with three channel = "<< endl << " " << M3 << endl << endl;
M1.create(4,4, CV_8UC(2));
cout << "M1 = "<< endl << " " << M1 << endl << endl;
Scalar s1(1);
Scalar s2(1, 2);
Scalar s3(1, 2, 3);
Scalar s4(1, 2, 3, 4);
Scalar s5(1, 2, 3, 5);
// Scalar s(1, 2, 3, 5, 6, 7, 8, 9);
cout << "scalar s1 "<< endl << " " << s1 << endl << endl;
cout << "scalar s2 "<< endl << " " << s2 << endl << endl;
cout << "scalar s3 "<< endl << " " << s3 << endl << endl;
cout << "scalar s4 "<< endl << " " << s4 << endl << endl;
cout << "scalar s5 "<< endl << " " << s5 << endl << endl;
// cout << "scalar s5 "<< endl << " " << s << endl << endl;
}
http://stackoverflow.com/questions/8377091/what-are-the-differences-between-
cv-8u-and-cv-32f-and-what-should-i-worry-about
http://docs.opencv.org/java/org/opencv/core/CvType.html
注释: 只有二位的matrix可以打印,多维的话,你自己需要写输出方法
ssh远程linux机器时,如何启动X11转发
X11 forwarding needs to be enabled on both the client side and the server
side.
On the client side, the -X (capital X) option to ssh enables X11 forwarding,
and you can make this the default (for all connections or for a specific
conection) with ForwardX11 yes in ~/.ssh/config.
On the server side, X11Forwarding yes must specified in /etc/ssh/sshd_config.
Note that the default is no forwarding (some distributions turn it on in their
default /etc/ssh/sshd_config), and that the user cannot override this setting.
The xauth program must be installed on the server side. If there are any X11
programs there, it’s very likely that xauth will be there. In the unlikely
case xauth was installed in a nonstandard location, it can be called through
~/.ssh/rc (on the server!).
Note that you do not need to set any environment variables on the server.
DISPLAY and XAUTHORITY will automatically be set to their proper values. If
you run ssh and DISPLAY is not set, it means ssh is not forwarding the X11
connection.
To confirm that ssh is forwarding X11, check for a line containing Requesting
X11 forwarding in the ssh -v -X output. Note that the server won’t reply
either way.
http://unix.stackexchange.com/questions/12755/how-to-forward-x-over-ssh-
from-ubuntu-machine
javascript中的document.getDocumentById返还null
1. 背景
我想做一个起点自动投推荐票的firefox插件,希望插件自己点击投推荐票dialog中的提交button,
但是我使用document.getDocumentById一直返回的是null,然后我就查找原因。
2.
最后发现投推荐票的dialog是用iframe实现的,但是当前的页面属于另外一个iframe,它的document中根本没有提交button的id(btn_OK)。
所以只能对当前所有的frame进行遍历,一个一个的找,如果找到的话调用click方法就好了,以下是方法的原型:
var targetId = "btn_OK"
var target = document.getElementById(targetId);
if(target != null) {
//do something
}
var iframes = document.getElementsByTagName('iframe'); //all iframes on page
console.log("total frame " + iframes.length);
var errCount = 0;
for(var i=0; i<iframes.length; i++){
console.log("current frame is: " + iframes[i]);
var iframeDocument;
try {
iframeDocument = iframes[i].contentDocument || iframes[i].contentWindow.document;
target = iframeDocument.getElementById(targetId);
console.log(target);
}
catch (err){
errCount ++;
console.log(err);
}
}
因为不同的iframe有可能是不同的domain的,所有需要try catch。
在Java中如何通过反射找到一个变量,这个变量的类型是指定的类型
1. 说明以下的代码是我从Spring中抓出来的,然后加了一些我认为对自己有用的方法。
2. 直接上代码,看不懂的请留言。
3. 如何解决标题中提到的问题呢?请查找findAllField方法。
ReflectionUtils.java
package test.util;
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.UndeclaredThrowableException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.core.runtime.Assert;
/**
* Simple utility class for working with the reflection API and handling
* reflection exceptions.
*
* <p>Only intended for internal use.
*
* @author Juergen Hoeller
* @author Rob Harrop
* @author Rod Johnson
* @author Costin Leau
* @author Sam Brannen
* @author Chris Beams
* @author Roy Clarkson
* @author jialiang
* @since 1.1
*/
public abstract class ReflectionUtils {
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code>. Searches all superclasses up to {@link Object}.
* @param clazz the class to introspect
* @param name the name of the field
* @return the corresponding Field object, or <code>null</code> if not found
*/
public static Field findField(Class<?> clazz, String name) {
return findField(clazz, name, null);
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> and/or {@link Class type}. Searches all superclasses
* up to {@link Object}.
* @param clazz the class to introspect
* @param name the name of the field (may be <code>null</code> if type is specified)
* @param type the type of the field (may be <code>null</code> if name is specified)
* @return the corresponding Field object, or <code>null</code> if not found
*/
public static Field findField(Class<?> clazz, String name, Class<?> type) {
Assert.isNotNull(clazz, "Class must not be null");
Assert.isTrue(name != null || type != null, "Either name or type of the field must be specified");
Class<?> searchType = clazz;
while (!Object.class.equals(searchType) && searchType != null) {
Field[] fields = searchType.getDeclaredFields();
for (Field field : fields) {
if ((name == null || name.equals(field.getName())) && (type == null || type.equals(field.getType()))) {
return field;
}
}
searchType = searchType.getSuperclass();
}
return null;
}
/**
* Attempt to find a {@link Field field} on the supplied {@link Class} with the
* supplied <code>name</code> and/or {@link Class type}. Searches all superclasses
* up to {@link Object}.
* @param clazz the class to introspect
* @param name the name of the field (may be <code>null</code> if type is specified)
* @param type the type of the field, must not be <code>null</code>
* @return the corresponding Field object, or <code>null</code> if not found
*/
public static List<Field> findAllField(Class<?> clazz, String name, Class<?> type) {
Assert.isNotNull(clazz, "Class must not be null");
Assert.isNotNull(type, "The type of filed must not be null");
List<Field> list = new ArrayList<Field>();
Class<?> searchType = clazz;
while (!Object.class.equals(searchType) && searchType != null) {
Field[] fields = searchType.getDeclaredFields();
for (Field field : fields) {
if ((name == null || name.equals(field.getName())) && type.equals(field.getType())) {
list.add(field);
}
}
searchType = searchType.getSuperclass();
}
return list;
}
public static List<Field> findAllField(Class<?> clazz, Class<?> type) {
return findAllField(clazz, null, type);
}
/**
* Set the field represented by the supplied {@link Field field object} on the
* specified {@link Object target object} to the specified <code>value</code>.
* In accordance with {@link Field#set(Object, Object)} semantics, the new value
* is automatically unwrapped if the underlying field has a primitive type.
* <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
* @param field the field to set
* @param target the target object on which to set the field
* @param value the value to set; may be <code>null</code>
*/
public static void setField(Field field, Object target, Object value) {
try {
field.set(target, value);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
throw new IllegalStateException("Unexpected reflection exception - " + ex.getClass().getName() + ": "
+ ex.getMessage());
}
}
/**
* Get the field represented by the supplied {@link Field field object} on the
* specified {@link Object target object}. In accordance with {@link Field#get(Object)}
* semantics, the returned value is automatically wrapped if the underlying field
* has a primitive type.
* <p>Thrown exceptions are handled via a call to {@link #handleReflectionException(Exception)}.
* @param field the field to get
* @param target the target object from which to get the field
* @return the field's current value
*/
public static Object getField(Field field, Object target) {
try {
field.setAccessible(true);
return field.get(target);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
throw new IllegalStateException(
"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
}
}
public static Object getField(String fieldName, Object target) {
Field field = findField(target.getClass(), fieldName);
if(field == null) {
return null;
}
try {
field.setAccessible(true);
return field.get(target);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
throw new IllegalStateException(
"Unexpected reflection exception - " + ex.getClass().getName() + ": " + ex.getMessage());
}
}
/**
* Attempt to find a {@link Method} on the supplied class with the supplied name
* and no parameters. Searches all superclasses up to <code>Object</code>.
* <p>Returns <code>null</code> if no {@link Method} can be found.
* @param clazz the class to introspect
* @param name the name of the method
* @return the Method object, or <code>null</code> if none found
*/
public static Method findMethod(Class<?> clazz, String name) {
return findMethod(clazz, name, new Class[0]);
}
public static Object invokeMethod(Object target, String name) {
Assert.isNotNull(target, "target must not be null");
Assert.isNotNull(name, "Method name must not be null");
Method m = findMethod(target.getClass(), name);
if(m == null) {
return null;
}
makeAccessible(m);
return invokeMethod(m, target);
}
public static Object invokeMethod(Object target, String name, Object... args) {
Assert.isNotNull(target, "target must not be null");
Assert.isNotNull(name, "Method name must not be null");
Method m = findMethod(target.getClass(), name);
if(m == null) {
return null;
}
return invokeMethod(m, target, args);
}
/**
* Attempt to find a {@link Method} on the supplied class with the supplied name
* and parameter types. Searches all superclasses up to <code>Object</code>.
* <p>Returns <code>null</code> if no {@link Method} can be found.
* @param clazz the class to introspect
* @param name the name of the method
* @param paramTypes the parameter types of the method
* (may be <code>null</code> to indicate any signature)
* @return the Method object, or <code>null</code> if none found
*/
public static Method findMethod(Class<?> clazz, String name, Class<?>... paramTypes) {
Assert.isNotNull(clazz, "Class must not be null");
Assert.isNotNull(name, "Method name must not be null");
Class<?> searchType = clazz;
while (searchType != null) {
Method[] methods = (searchType.isInterface() ? searchType.getMethods() : searchType.getDeclaredMethods());
for (Method method : methods) {
if (name.equals(method.getName())
&& (paramTypes == null || Arrays.equals(paramTypes, method.getParameterTypes()))) {
return method;
}
}
searchType = searchType.getSuperclass();
}
return null;
}
/**
* Invoke the specified {@link Method} against the supplied target object with no arguments.
* The target object can be <code>null</code> when invoking a static {@link Method}.
* <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
* @param method the method to invoke
* @param target the target object to invoke the method on
* @return the invocation result, if any
* @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
*/
public static Object invokeMethod(Method method, Object target) {
return invokeMethod(method, target, new Object[0]);
}
/**
* Invoke the specified {@link Method} against the supplied target object with the
* supplied arguments. The target object can be <code>null</code> when invoking a
* static {@link Method}.
* <p>Thrown exceptions are handled via a call to {@link #handleReflectionException}.
* @param method the method to invoke
* @param target the target object to invoke the method on
* @param args the invocation arguments (may be <code>null</code>)
* @return the invocation result, if any
*/
public static Object invokeMethod(Method method, Object target, Object... args) {
try {
return method.invoke(target, args);
}
catch (Exception ex) {
handleReflectionException(ex);
}
throw new IllegalStateException("Should never get here");
}
/**
* Invoke the specified JDBC API {@link Method} against the supplied target
* object with no arguments.
* @param method the method to invoke
* @param target the target object to invoke the method on
* @return the invocation result, if any
* @throws SQLException the JDBC API SQLException to rethrow (if any)
* @see #invokeJdbcMethod(java.lang.reflect.Method, Object, Object[])
*/
public static Object invokeJdbcMethod(Method method, Object target) throws SQLException {
return invokeJdbcMethod(method, target, new Object[0]);
}
/**
* Invoke the specified JDBC API {@link Method} against the supplied target
* object with the supplied arguments.
* @param method the method to invoke
* @param target the target object to invoke the method on
* @param args the invocation arguments (may be <code>null</code>)
* @return the invocation result, if any
* @throws SQLException the JDBC API SQLException to rethrow (if any)
* @see #invokeMethod(java.lang.reflect.Method, Object, Object[])
*/
public static Object invokeJdbcMethod(Method method, Object target, Object... args) throws SQLException {
try {
return method.invoke(target, args);
}
catch (IllegalAccessException ex) {
handleReflectionException(ex);
}
catch (InvocationTargetException ex) {
if (ex.getTargetException() instanceof SQLException) {
throw (SQLException) ex.getTargetException();
}
handleInvocationTargetException(ex);
}
throw new IllegalStateException("Should never get here");
}
/**
* Handle the given reflection exception. Should only be called if no
* checked exception is expected to be thrown by the target method.
* <p>Throws the underlying RuntimeException or Error in case of an
* InvocationTargetException with such a root cause. Throws an
* IllegalStateException with an appropriate message else.
* @param ex the reflection exception to handle
*/
public static void handleReflectionException(Exception ex) {
if (ex instanceof NoSuchMethodException) {
throw new IllegalStateException("Method not found: " + ex.getMessage());
}
if (ex instanceof IllegalAccessException) {
throw new IllegalStateException("Could not access method: " + ex.getMessage());
}
if (ex instanceof InvocationTargetException) {
handleInvocationTargetException((InvocationTargetException) ex);
}
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
throw new UndeclaredThrowableException(ex);
}
/**
* Handle the given invocation target exception. Should only be called if no
* checked exception is expected to be thrown by the target method.
* <p>Throws the underlying RuntimeException or Error in case of such a root
* cause. Throws an IllegalStateException else.
* @param ex the invocation target exception to handle
*/
public static void handleInvocationTargetException(InvocationTargetException ex) {
rethrowRuntimeException(ex.getTargetException());
}
/**
* Rethrow the given {@link Throwable exception}, which is presumably the
* <em>target exception</em> of an {@link InvocationTargetException}. Should
* only be called if no checked exception is expected to be thrown by the
* target method.
* <p>Rethrows the underlying exception cast to an {@link RuntimeException} or
* {@link Error} if appropriate; otherwise, throws an
* {@link IllegalStateException}.
* @param ex the exception to rethrow
* @throws RuntimeException the rethrown exception
*/
public static void rethrowRuntimeException(Throwable ex) {
if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
throw new UndeclaredThrowableException(ex);
}
/**
* Rethrow the given {@link Throwable exception}, which is presumably the
* <em>target exception</em> of an {@link InvocationTargetException}. Should
* only be called if no checked exception is expected to be thrown by the
* target method.
* <p>Rethrows the underlying exception cast to an {@link Exception} or
* {@link Error} if appropriate; otherwise, throws an
* {@link IllegalStateException}.
* @param ex the exception to rethrow
* @throws Exception the rethrown exception (in case of a checked exception)
*/
public static void rethrowException(Throwable ex) throws Exception {
if (ex instanceof Exception) {
throw (Exception) ex;
}
if (ex instanceof Error) {
throw (Error) ex;
}
throw new UndeclaredThrowableException(ex);
}
/**
* Determine whether the given method explicitly declares the given
* exception or one of its superclasses, which means that an exception of
* that type can be propagated as-is within a reflective invocation.
* @param method the declaring method
* @param exceptionType the exception to throw
* @return <code>true</code> if the exception can be thrown as-is;
* <code>false</code> if it needs to be wrapped
*/
public static boolean declaresException(Method method, Class<?> exceptionType) {
Assert.isNotNull(method, "Method must not be null");
Class<?>[] declaredExceptions = method.getExceptionTypes();
for (Class<?> declaredException : declaredExceptions) {
if (declaredException.isAssignableFrom(exceptionType)) {
return true;
}
}
return false;
}
/**
* Determine whether the given field is a "public static final" constant.
* @param field the field to check
*/
public static boolean isPublicStaticFinal(Field field) {
int modifiers = field.getModifiers();
return (Modifier.isPublic(modifiers) && Modifier.isStatic(modifiers) && Modifier.isFinal(modifiers));
}
/**
* Determine whether the given method is an "equals" method.
* @see java.lang.Object#equals(Object)
*/
public static boolean isEqualsMethod(Method method) {
if (method == null || !method.getName().equals("equals")) {
return false;
}
Class<?>[] paramTypes = method.getParameterTypes();
return (paramTypes.length == 1 && paramTypes[0] == Object.class);
}
/**
* Determine whether the given method is a "hashCode" method.
* @see java.lang.Object#hashCode()
*/
public static boolean isHashCodeMethod(Method method) {
return (method != null && method.getName().equals("hashCode") && method.getParameterTypes().length == 0);
}
/**
* Determine whether the given method is a "toString" method.
* @see java.lang.Object#toString()
*/
public static boolean isToStringMethod(Method method) {
return (method != null && method.getName().equals("toString") && method.getParameterTypes().length == 0);
}
/**
* Determine whether the given method is originally declared by {@link java.lang.Object}.
*/
public static boolean isObjectMethod(Method method) {
try {
Object.class.getDeclaredMethod(method.getName(), method.getParameterTypes());
return true;
} catch (SecurityException ex) {
return false;
} catch (NoSuchMethodException ex) {
return false;
}
}
/**
* Make the given field accessible, explicitly setting it accessible if
* necessary. The <code>setAccessible(true)</code> method is only called
* when actually necessary, to avoid unnecessary conflicts with a JVM
* SecurityManager (if active).
* @param field the field to make accessible
* @see java.lang.reflect.Field#setAccessible
*/
public static void makeAccessible(Field field) {
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) ||
Modifier.isFinal(field.getModifiers())) && !field.isAccessible()) {
field.setAccessible(true);
}
}
/**
* Make the given method accessible, explicitly setting it accessible if
* necessary. The <code>setAccessible(true)</code> method is only called
* when actually necessary, to avoid unnecessary conflicts with a JVM
* SecurityManager (if active).
* @param method the method to make accessible
* @see java.lang.reflect.Method#setAccessible
*/
public static void makeAccessible(Method method) {
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
&& !method.isAccessible()) {
method.setAccessible(true);
}
}
/**
* Make the given constructor accessible, explicitly setting it accessible
* if necessary. The <code>setAccessible(true)</code> method is only called
* when actually necessary, to avoid unnecessary conflicts with a JVM
* SecurityManager (if active).
* @param ctor the constructor to make accessible
* @see java.lang.reflect.Constructor#setAccessible
*/
public static void makeAccessible(Constructor<?> ctor) {
if ((!Modifier.isPublic(ctor.getModifiers()) || !Modifier.isPublic(ctor.getDeclaringClass().getModifiers()))
&& !ctor.isAccessible()) {
ctor.setAccessible(true);
}
}
/**
* Perform the given callback operation on all matching methods of the given
* class and superclasses.
* <p>The same named method occurring on subclass and superclass will appear
* twice, unless excluded by a {@link MethodFilter}.
* @param clazz class to start looking at
* @param mc the callback to invoke for each method
* @see #doWithMethods(Class, MethodCallback, MethodFilter)
*/
public static void doWithMethods(Class<?> clazz, MethodCallback mc) throws IllegalArgumentException {
doWithMethods(clazz, mc, null);
}
/**
* Perform the given callback operation on all matching methods of the given
* class and superclasses (or given interface and super-interfaces).
* <p>The same named method occurring on subclass and superclass will appear
* twice, unless excluded by the specified {@link MethodFilter}.
* @param clazz class to start looking at
* @param mc the callback to invoke for each method
* @param mf the filter that determines the methods to apply the callback to
*/
public static void doWithMethods(Class<?> clazz, MethodCallback mc, MethodFilter mf)
throws IllegalArgumentException {
// Keep backing up the inheritance hierarchy.
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
if (mf != null && !mf.matches(method)) {
continue;
}
try {
mc.doWith(method);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException("Shouldn't be illegal to access method '" + method.getName()
+ "': " + ex);
}
}
if (clazz.getSuperclass() != null) {
doWithMethods(clazz.getSuperclass(), mc, mf);
}
else if (clazz.isInterface()) {
for (Class<?> superIfc : clazz.getInterfaces()) {
doWithMethods(superIfc, mc, mf);
}
}
}
/**
* Get all declared methods on the leaf class and all superclasses. Leaf
* class methods are included first.
*/
public static Method[] getAllDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {
final List<Method> methods = new ArrayList<Method>(32);
doWithMethods(leafClass, new MethodCallback() {
public void doWith(Method method) {
methods.add(method);
}
});
return methods.toArray(new Method[methods.size()]);
}
/**
* Get the unique set of declared methods on the leaf class and all superclasses. Leaf
* class methods are included first and while traversing the superclass hierarchy any methods found
* with signatures matching a method already included are filtered out.
*/
public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {
final List<Method> methods = new ArrayList<Method>(32);
doWithMethods(leafClass, new MethodCallback() {
public void doWith(Method method) {
Method methodBeingOverriddenWithCovariantReturnType = null;
for (Method existingMethod : methods) {
if (method.getName().equals(existingMethod.getName()) &&
Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {
// is this a covariant return type situation?
if (existingMethod.getReturnType() != method.getReturnType() &&
existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {
methodBeingOverriddenWithCovariantReturnType = existingMethod;
}
break;
}
}
if (methodBeingOverriddenWithCovariantReturnType != null) {
methods.remove(methodBeingOverriddenWithCovariantReturnType);
}
}
});
return methods.toArray(new Method[methods.size()]);
}
/**
* Invoke the given callback on all fields in the target class, going up the
* class hierarchy to get all declared fields.
* @param clazz the target class to analyze
* @param fc the callback to invoke for each field
*/
public static void doWithFields(Class<?> clazz, FieldCallback fc) throws IllegalArgumentException {
doWithFields(clazz, fc, null);
}
/**
* Invoke the given callback on all fields in the target class, going up the
* class hierarchy to get all declared fields.
* @param clazz the target class to analyze
* @param fc the callback to invoke for each field
* @param ff the filter that determines the fields to apply the callback to
*/
public static void doWithFields(Class<?> clazz, FieldCallback fc, FieldFilter ff)
throws IllegalArgumentException {
// Keep backing up the inheritance hierarchy.
Class<?> targetClass = clazz;
do {
Field[] fields = targetClass.getDeclaredFields();
for (Field field : fields) {
// Skip static and final fields.
if (ff != null && !ff.matches(field)) {
continue;
}
try {
fc.doWith(field);
}
catch (IllegalAccessException ex) {
throw new IllegalStateException(
"Shouldn't be illegal to access field '" + field.getName() + "': " + ex);
}
}
targetClass = targetClass.getSuperclass();
}
while (targetClass != null && targetClass != Object.class);
}
/**
* Given the source object and the destination, which must be the same class
* or a subclass, copy all fields, including inherited fields. Designed to
* work on objects with public no-arg constructors.
* @throws IllegalArgumentException if the arguments are incompatible
*/
public static void shallowCopyFieldState(final Object src, final Object dest) throws IllegalArgumentException {
if (src == null) {
throw new IllegalArgumentException("Source for field copy cannot be null");
}
if (dest == null) {
throw new IllegalArgumentException("Destination for field copy cannot be null");
}
if (!src.getClass().isAssignableFrom(dest.getClass())) {
throw new IllegalArgumentException("Destination class [" + dest.getClass().getName()
+ "] must be same or subclass as source class [" + src.getClass().getName() + "]");
}
doWithFields(src.getClass(), new FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
makeAccessible(field);
Object srcValue = field.get(src);
field.set(dest, srcValue);
}
}, COPYABLE_FIELDS);
}
/**
* Action to take on each method.
*/
public interface MethodCallback {
/**
* Perform an operation using the given method.
* @param method the method to operate on
*/
void doWith(Method method) throws IllegalArgumentException, IllegalAccessException;
}
/**
* Callback optionally used to filter methods to be operated on by a method callback.
*/
public interface MethodFilter {
/**
* Determine whether the given method matches.
* @param method the method to check
*/
boolean matches(Method method);
}
/**
* Callback interface invoked on each field in the hierarchy.
*/
public interface FieldCallback {
/**
* Perform an operation using the given field.
* @param field the field to operate on
*/
void doWith(Field field) throws IllegalArgumentException, IllegalAccessException;
}
/**
* Callback optionally used to filter fields to be operated on by a field callback.
*/
public interface FieldFilter {
/**
* Determine whether the given field matches.
* @param field the field to check
*/
boolean matches(Field field);
}
/**
* Pre-built FieldFilter that matches all non-static, non-final fields.
*/
public static FieldFilter COPYABLE_FIELDS = new FieldFilter() {
public boolean matches(Field field) {
return !(Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers()));
}
};
/**
* Pre-built MethodFilter that matches all non-bridge methods.
*/
public static MethodFilter NON_BRIDGED_METHODS = new MethodFilter() {
public boolean matches(Method method) {
return !method.isBridge();
}
};
/**
* Pre-built MethodFilter that matches all non-bridge methods
* which are not declared on <code>java.lang.Object</code>.
*/
public static MethodFilter USER_DECLARED_METHODS = new MethodFilter() {
public boolean matches(Method method) {
return (!method.isBridge() && method.getDeclaringClass() != Object.class);
}
};
}
Eclipse 4.x中Command是如何映射到Handler的
1. Eclipse中的Command模式,使得具体的实现和Command定义分离,便于维护。
但是在Debug的时候,或者没有souce code的时候,我们想知道每一个commandId对应的Handler是什么,怎么办?
2. 在Eclipse
4.x中,其实当Eclipse启动完成后,它已经创建了commandId和对应Handler的Map,保存在EclipseContext中,
然后通过反射调用到对应的Handler。 见下图:
Eclipse是在上图中我框出来的地方,通过commandId在EclipseContext中查找到。
3. 如何将EclipseContext中的Handler都dump出来呢?
一句话,反射。
注意,以下代码我只在Eclipse 4.3.0上测试通过。
//try to print all handler in eclipse 4.x
result = ReflectionUtils.getField("e4Context", site);
if(!isSuccess(result)) {
return;
}
if(result instanceof IEclipseContext) {
IEclipseContext context = (IEclipseContext)result;
printHandlerForEclipseContext(context, 0);
}
@SuppressWarnings("unchecked")
private void printHandlerForEclipseContext(IEclipseContext context, int step) {
Assert.isNotNull(context);
Object result = null;
if(step != 0) {
result = ReflectionUtils.getField("localValueComputations", context);
} else {
result = ReflectionUtils.getField("localValues", context);
}
if(!isSuccess(result)) {
return;
}
if(result instanceof Map) {
String stepString = makeStep(step);
Map<String, Object> localValueComputations = (Map<String, Object>)result;
for (String string : localValueComputations.keySet()) {
Object object = localValueComputations.get(string);
String last = object.toString();
if(string.startsWith("legacy::handler::")) {
if(object instanceof ArrayList) {
ArrayList list = (ArrayList)object;
//TODO may be more than one item in list
object = list.get(0);
if(object instanceof IHandlerActivation) {
IHandlerActivation activation = (IHandlerActivation)object;
last = activation.getHandler().toString();
}
}
}
System.out.println(stepString + string + ", " + last);
}
}
result = null;
result = ReflectionUtils.invokeMethod(context, "getChildren");
if(!isSuccess(result)) {
return;
}
if(result instanceof Set) {
Set<IEclipseContext> children = (Set<IEclipseContext>)result;
Iterator<IEclipseContext> iterator = children.iterator();
IEclipseContext child = null;
int moreStep = step + 1;
while(iterator.hasNext()) {
child = iterator.next();
printHandlerForEclipseContext(child, moreStep);
}
step ++;
}
}
以下是我的屏幕输出的一部分,输出格式为:commandId, Handler
…
legacy::handler::org.eclipse.ui.edit.text.recenter,
ActionHandler(org.eclipse.ui.texteditor.RecenterAction@7efaa9e2)
legacy::handler::org.eclipse.jdt.ui.edit.text.java.search.declarations.in.hierarchy,
ActionHandler(org.eclipse.jdt.ui.actions.FindDeclarationsInHierarchyAction@14c26e4a)
legacy::handler::org.eclipse.jdt.ui.edit.text.java.search.declarations.in.project,
ActionHandler(org.eclipse.jdt.ui.actions.FindDeclarationsInProjectAction@174043f5)
legacy::handler::org.eclipse.jdt.ui.edit.text.java.surround.with.try.multicatch,
ActionHandler(org.eclipse.jdt.ui.actions.SurroundWithTryMultiCatchAction@49e3c996)
legacy::handler::org.eclipse.jdt.ui.edit.text.java.override.methods,
ActionHandler(org.eclipse.jdt.ui.actions.OverrideMethodsAction@11e18e8c)
legacy::handler:: org.eclipse.ui.edit.findPrevious , ActionHandler(
org.eclipse.ui.texteditor.FindNextAction @69d5ee81)
handler::org.eclipse.jdt.ui.edit.text.java.remove.block.comment,
org.eclipse.ui.internal.handlers.LegacyHandlerService$HandlerSelectionFunction@207462c0
…