List of usage examples for java.lang.reflect AccessibleObject isAccessible
@Deprecated(since = "9") public boolean isAccessible()
From source file:Utils.java
public static void makeAccessible(final AccessibleObject object) { if (!object.isAccessible()) { if (System.getSecurityManager() == null) { object.setAccessible(true);// w w w.j av a2s. co m } else { AccessController.doPrivileged(new PrivilegedAction<Object>() { public Object run() { object.setAccessible(true); return null; } }); } } }
From source file:ch.algotrader.util.FieldUtil.java
private static void setAccessible(final AccessibleObject object) { if (object.isAccessible()) return;/* w w w .ja v a 2 s . c om*/ AccessController.doPrivileged((PrivilegedAction<Object>) () -> { object.setAccessible(true); return null; }); }
From source file:Main.java
public static void checkAndFixAccess(Member paramMember) { AccessibleObject localAccessibleObject = (AccessibleObject) paramMember; try {/*from w w w . j a va 2 s . c o m*/ localAccessibleObject.setAccessible(true); return; } catch (SecurityException localSecurityException) { while (localAccessibleObject.isAccessible()) ; Class localClass = paramMember.getDeclaringClass(); throw new IllegalArgumentException("Can not access " + paramMember + " (from class " + localClass.getName() + "; failed to set access: " + localSecurityException.getMessage()); } }
From source file:Main.java
/** * Method called to check if we can use the passed method or constructor * (wrt access restriction -- public methods can be called, others * usually not); and if not, if there is a work-around for * the problem.//from w ww.j a v a2 s . co m */ public static void checkAndFixAccess(Member member) { // We know all members are also accessible objects... AccessibleObject ao = (AccessibleObject) member; /* 14-Jan-2009, tatu: It seems safe and potentially beneficial to * always to make it accessible (latter because it will force * skipping checks we have no use for...), so let's always call it. */ //if (!ao.isAccessible()) { try { ao.setAccessible(true); } catch (SecurityException se) { /* 17-Apr-2009, tatu: Related to [JACKSON-101]: this can fail on * platforms like EJB and Google App Engine); so let's * only fail if we really needed it... */ if (!ao.isAccessible()) { Class<?> declClass = member.getDeclaringClass(); throw new IllegalArgumentException("Can not access " + member + " (from class " + declClass.getName() + "; failed to set access: " + se.getMessage()); } } //} }
From source file:com.clarkparsia.empire.annotation.RdfGenerator.java
/** * Return the given Java bean as a set of RDF triples * @param theObj the object/*www . ja v a2s. c o m*/ * @return the object represented as RDF triples * @throws InvalidRdfException thrown if the object cannot be transformed into RDF. */ public static Graph asRdf(final Object theObj) throws InvalidRdfException { if (theObj == null) { return null; } Object aObj = theObj; if (aObj instanceof ProxyHandler) { aObj = ((ProxyHandler) aObj).mProxy.value(); } else { try { if (aObj.getClass().getDeclaredField("handler") != null) { Field aProxy = aObj.getClass().getDeclaredField("handler"); aObj = ((ProxyHandler) BeanReflectUtil.safeGet(aProxy, aObj)).mProxy.value(); } } catch (InvocationTargetException e) { // this is probably an error, we know its a proxy object, but can't get the proxied object throw new InvalidRdfException("Could not access proxy object", e); } catch (NoSuchFieldException e) { // this is probably ok. } } RdfsClass aClass = asValidRdfClass(aObj); Resource aSubj = id(aObj); addNamespaces(aObj.getClass()); GraphBuilder aBuilder = new GraphBuilder(); Collection<AccessibleObject> aAccessors = new HashSet<AccessibleObject>(); aAccessors.addAll(getAnnotatedFields(aObj.getClass())); aAccessors.addAll(getAnnotatedGetters(aObj.getClass(), true)); try { ResourceBuilder aRes = aBuilder.instance( aBuilder.getValueFactory().createURI(PrefixMapping.GLOBAL.uri(aClass.value())), aSubj); for (AccessibleObject aAccess : aAccessors) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Getting rdf for : {}", aAccess); } AsValueFunction aFunc = new AsValueFunction(aAccess); if (aAccess.isAnnotationPresent(Transient.class) || (aAccess instanceof Field && Modifier.isTransient(((Field) aAccess).getModifiers()))) { // transient fields or accessors with the Transient annotation do not get converted. continue; } RdfProperty aPropertyAnnotation = BeanReflectUtil.getAnnotation(aAccess, RdfProperty.class); String aBase = "urn:empire:clark-parsia:"; if (aRes instanceof URI) { aBase = ((URI) aRes).getNamespace(); } URI aProperty = aPropertyAnnotation != null ? aBuilder.getValueFactory() .createURI(PrefixMapping.GLOBAL.uri(aPropertyAnnotation.value())) : (aAccess instanceof Field ? aBuilder.getValueFactory().createURI(aBase + ((Field) aAccess).getName()) : null); boolean aOldAccess = aAccess.isAccessible(); setAccessible(aAccess, true); Object aValue = get(aAccess, aObj); setAccessible(aAccess, aOldAccess); if (aValue == null || aValue.toString().equals("")) { continue; } else if (Collection.class.isAssignableFrom(aValue.getClass())) { @SuppressWarnings("unchecked") List<Value> aValueList = asList(aAccess, (Collection<?>) Collection.class.cast(aValue)); if (aValueList.isEmpty()) { continue; } if (aPropertyAnnotation.isList()) { aRes.addProperty(aProperty, aValueList); } else { for (Value aVal : aValueList) { aRes.addProperty(aProperty, aVal); } } } else { aRes.addProperty(aProperty, aFunc.apply(aValue)); } } } catch (IllegalAccessException e) { throw new InvalidRdfException(e); } catch (RuntimeException e) { throw new InvalidRdfException(e); } catch (InvocationTargetException e) { throw new InvalidRdfException("Cannot invoke method", e); } return aBuilder.graph(); }
From source file:com.clarkparsia.empire.annotation.RdfGenerator.java
/** * Populate the fields of the current instance from the RDF indiviual with the given URI * @param theObj the Java object to populate * @param theSource the KB to get the RDF data from * @param <T> the type of the class being populated * @return theObj, populated from the specified DataSource * @throws InvalidRdfException thrown if the object does not support the RDF JPA API. * @throws DataSourceException thrown if there is an error retrieving data from the database */// w w w . ja v a2s. co m @SuppressWarnings("unchecked") private synchronized static <T> T fromRdf(T theObj, DataSource theSource) throws InvalidRdfException, DataSourceException { final SupportsRdfId aTmpSupportsRdfId = asSupportsRdfId(theObj); final SupportsRdfId.RdfKey theKeyObj = aTmpSupportsRdfId.getRdfId(); long start = System.currentTimeMillis(), start1 = System.currentTimeMillis(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Converting {} to RDF.", theObj); } if (OBJECT_M.containsKey(theKeyObj)) { // TODO: this is probably a safe cast, i dont see how something w/ the same URI, which should be the same // object would change types return (T) OBJECT_M.get(theKeyObj); } try { OBJECT_M.put(theKeyObj, theObj); Graph aGraph = DataSourceUtil.describe(theSource, theObj); if (aGraph.size() == 0) { return theObj; } final Resource aTmpRes = EmpireUtil.asResource(aTmpSupportsRdfId); Set<URI> aProps = new HashSet<URI>(); Iterator<Statement> sIter = aGraph.match(aTmpRes, null, null); while (sIter.hasNext()) { Statement aStmt = sIter.next(); aProps.add(aStmt.getPredicate()); } final SupportsRdfId aSupportsRdfId = asSupportsRdfId(theObj); final EmpireGenerated aEmpireGenerated = asEmpireGenerated(theObj); aEmpireGenerated.setAllTriples(aGraph); OBJECT_M.put(theKeyObj, theObj); final Resource aRes = EmpireUtil.asResource(aSupportsRdfId); addNamespaces(theObj.getClass()); Map<URI, AccessibleObject> theCachedMap = ACCESSORS_BY_CLASS.get(theObj.getClass()); if (theCachedMap == null) { theCachedMap = cacheAccessibles(theObj.getClass(), aRes); } Set<URI> aUsedProps = new HashSet<URI>(); for (URI aProp : aProps) { AccessibleObject aAccess = theCachedMap.get(aProp); if (aAccess == null && RDF.TYPE.equals(aProp)) { // TODO: the following block should be entirely removed (leaving continue only) // right now, leaving it until the code review: code review before removing the following block // my understanding is that the following block was only necessary when having a support for a single-typed objects, // which is no longer the case // we can skip the rdf:type property. it's basically assigned in the @RdfsClass annotation on the // java class, so we can figure it out later if need be. TODO: of course, if something has multiple types // that information is lost, which is not good. /* URI aType = (URI) aGraph.getValue(aRes, aProp); if (!TYPE_TO_CLASS.containsKey(aType) || !TYPE_TO_CLASS.get(aType).isAssignableFrom(theObj.getClass())) { if (TYPE_TO_CLASS.containsKey(aType) && !TYPE_TO_CLASS.get(aType).getName().equals(theObj.getClass().getName())) { // TODO: this might just be an error LOGGER.warn("Asserted rdf:type of the individual does not match the rdf:type annotation on the object. " + aType + " " + TYPE_TO_CLASS.get(aType) + " " + theObj.getClass() + " " +TYPE_TO_CLASS.get(aType).isAssignableFrom(theObj.getClass())+ " " +TYPE_TO_CLASS.get(aType).equals(theObj.getClass()) + " " + TYPE_TO_CLASS.get(aType).getName().equals(theObj.getClass().getName())); } else { // if they're not equals() or isAssignableFrom, but have the same name, this is usually // means that the class loaders don't match. so probably not an error, so no warning. } } */ continue; } else if (aAccess == null) { // this must be data that is not covered by the bean (perhaps accessible by a different view/bean for a differnent type of an individual) continue; } aUsedProps.add(aProp); ToObjectFunction aFunc = new ToObjectFunction(theSource, aRes, aAccess, aProp); Object aValue = aFunc.apply(GraphUtil.getObjects(aGraph, aRes, aProp)); boolean aOldAccess = aAccess.isAccessible(); try { setAccessible(aAccess, true); set(aAccess, theObj, aValue); } catch (InvocationTargetException e) { // oh crap throw new InvalidRdfException(e); } catch (IllegalAccessException e) { // this should not happen since we toggle the accessibility of the field, but we'll re-throw regardless throw new InvalidRdfException(e); } catch (IllegalArgumentException e) { // this is "likely" to happen. we'll get this exception if the rdf does not match the java. for example // if something is specified to be an int in the java class, but it typed as a float (though down conversion // in that case might work) the set call will fail. // TODO: shouldnt this be an error? // LOGGER.info("Probable type mismatch: {} {}", aValue, aAccess); } catch (RuntimeException e) { // TODO: i dont like keying on a RuntimeException here to get the error condition, but since the // Function interface does not throw anything, this is the best we can do. maybe consider a // version of the Function interface that has a throws clause, it would make this more clear. // this was probably an error converting from a Value to an Object throw new InvalidRdfException(e); } finally { setAccessible(aAccess, aOldAccess); } } sIter = aGraph.match(aTmpRes, null, null); Graph aInstanceTriples = Graphs.newGraph(); while (sIter.hasNext()) { Statement aStmt = sIter.next(); if (aUsedProps.contains(aStmt.getPredicate())) { aInstanceTriples.add(aStmt); } } aEmpireGenerated.setInstanceTriples(aInstanceTriples); return theObj; } finally { OBJECT_M.remove(theKeyObj); } }
From source file:com.clark.func.Functions.java
/** * XXX Default access superclass workaround * /*from w ww .j av a2 s. co m*/ * When a public class has a default access superclass with public members, * these members are accessible. Calling them from compiled code works fine. * Unfortunately, on some JVMs, using reflection to invoke these members * seems to (wrongly) to prevent access even when the modifer is public. * Calling setAccessible(true) solves the problem but will only work from * sufficiently privileged code. Better workarounds would be gratefully * accepted. * * @param o * the AccessibleObject to set as accessible */ static void setAccessibleWorkaround(AccessibleObject o) { if (o == null || o.isAccessible()) { return; } Member m = (Member) o; if (Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); } catch (SecurityException e) { // ignore in favor of subsequent IllegalAccessException } } }
From source file:org.acoveo.tools.Reflection.java
/** * Make the given member accessible if it isn't already. *///from ww w . ja v a2 s . c o m private static void makeAccessible(AccessibleObject ao, int mods) { try { if (!Modifier.isPublic(mods) && !ao.isAccessible()) AccessController.doPrivileged(setAccessibleAction(ao, true)); } catch (SecurityException se) { throw new RuntimeException("Reflection security " + ao); } }
From source file:org.apache.bval.util.reflection.Reflection.java
/** * Set the accessibility of {@code o} to {@code accessible}. If running without a {@link SecurityManager} * and {@code accessible == false}, this call is ignored (because any code could reflectively make any * object accessible at any time).//w w w .j a v a 2 s. c om * @param o * @param accessible * @return whether a change was made. */ public static boolean setAccessible(final AccessibleObject o, boolean accessible) { if (o == null || o.isAccessible() == accessible) { return false; } if (!accessible && System.getSecurityManager() == null) { return false; } final Member m = (Member) o; // For public members whose declaring classes are public, we need do nothing: if (Modifier.isPublic(m.getModifiers()) && Modifier.isPublic(m.getDeclaringClass().getModifiers())) { return false; } o.setAccessible(accessible); return true; }
From source file:org.apache.openjpa.enhance.Reflection.java
/** * Make the given member accessible if it isn't already. *//*from w ww. ja va 2 s . c o m*/ private static void makeAccessible(AccessibleObject ao, int mods) { try { if (!Modifier.isPublic(mods) && !ao.isAccessible()) AccessController.doPrivileged(J2DoPrivHelper.setAccessibleAction(ao, true)); } catch (SecurityException se) { throw new UserException(_loc.get("reflect-security", ao)).setFatal(true); } }