Java Code Examples for java.lang.reflect.Method.isDefault()

The following are Jave code examples for showing how to use isDefault() of the java.lang.reflect.Method class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: urdriver   File: URScriptInvocationHandler.java   View Source Code Vote up 6 votes
private Object handleDefault(Object proxy, Method method, Object[] args) throws Throwable {
	// support default messages in interfaces
	if (method.isDefault()) {
		final Class<?> declaringClass = method.getDeclaringClass();
		final MethodHandles.Lookup lookup = MethodHandles.publicLookup().in(declaringClass);
		// ensure allowed mode will not check visibility
		final Field f = MethodHandles.Lookup.class.getDeclaredField("allowedModes");
		final int modifiers = f.getModifiers();
		if (Modifier.isFinal(modifiers)) { // should be done a single time
			final Field modifiersField = Field.class.getDeclaredField("modifiers");
			modifiersField.setAccessible(true);
			modifiersField.setInt(f, modifiers & ~Modifier.FINAL);
			f.setAccessible(true);
			f.set(lookup, MethodHandles.Lookup.PRIVATE);
		}
		return lookup.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
	}
	return null;
}
 
Example 2
Project: urdriver   File: URDashboardInvocationHandler.java   View Source Code Vote up 6 votes
private Object handleDefaultMessage(Object proxy, Method method, Object[] args) throws Throwable {
	// support default messages in interfaces
	if (method.isDefault()) {
		final Class<?> declaringClass = method.getDeclaringClass();
		final MethodHandles.Lookup lookup = MethodHandles.publicLookup().in(declaringClass);

		// ensure allowed mode will not check visibility
		final Field f = MethodHandles.Lookup.class.getDeclaredField("allowedModes");
		final int modifiers = f.getModifiers();
		if (Modifier.isFinal(modifiers)) { // should be done a single time
			final Field modifiersField = Field.class.getDeclaredField("modifiers");
			modifiersField.setAccessible(true);
			modifiersField.setInt(f, modifiers & ~Modifier.FINAL);
			f.setAccessible(true);
			f.set(lookup, MethodHandles.Lookup.PRIVATE);
		}
		return lookup.unreflectSpecial(method, declaringClass).bindTo(proxy).invokeWithArguments(args);
	}
	return null;
}
 
Example 3
Project: ProjectAres   File: ReflectiveParserManifest.java   View Source Code Vote up 6 votes
@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    // Give our delegate a chance to intercept, and cache the decision
    if(delegatedMethods.get(method, () -> method.getDeclaringClass() != Object.class &&
                                          Methods.hasOverrideIn(Delegate.class, method))) {
        return method.invoke(delegate, args);
    }

    // If we have a value for the property, return that
    final Object value = values.get(method);
    if(value != null) return value;

    // If there's no value, then the method MUST be callable (or the code is broken).
    // This can only fail for an abstract non-property method (which we should probably be checking for).
    if(method.isDefault()) {
        // invokeSuper doesn't understand default methods
        return defaultMethodHandles.get(method)
                                   .bindTo(obj)
                                   .invokeWithArguments(args);
    } else {
        return proxy.invokeSuper(obj, args);
    }
}
 
Example 4
Project: OpenJSharp   File: Class.java   View Source Code Vote up 6 votes
void removeLessSpecifics() {
    if (!hasDefaults())
        return;

    for (int i = 0; i < length; i++) {
        Method m = get(i);
        if  (m == null || !m.isDefault())
            continue;

        for (int j  = 0; j < length; j++) {
            if (i == j)
                continue;

            Method candidate = get(j);
            if (candidate == null)
                continue;

            if (!matchesNameAndDescriptor(m, candidate))
                continue;

            if (hasMoreSpecificClass(m, candidate))
                remove(j);
        }
    }
}
 
Example 5
Project: OpenJSharp   File: Class.java   View Source Code Vote up 6 votes
void removeLessSpecifics() {
    if (!hasDefaults())
        return;

    for (int i = 0; i < length; i++) {
        Method m = get(i);
        if  (m == null || !m.isDefault())
            continue;

        for (int j  = 0; j < length; j++) {
            if (i == j)
                continue;

            Method candidate = get(j);
            if (candidate == null)
                continue;

            if (!matchesNameAndDescriptor(m, candidate))
                continue;

            if (hasMoreSpecificClass(m, candidate))
                remove(j);
        }
    }
}
 
Example 6
Project: jdk8u-jdk   File: Class.java   View Source Code Vote up 6 votes
void removeLessSpecifics() {
    if (!hasDefaults())
        return;

    for (int i = 0; i < length; i++) {
        Method m = get(i);
        if  (m == null || !m.isDefault())
            continue;

        for (int j  = 0; j < length; j++) {
            if (i == j)
                continue;

            Method candidate = get(j);
            if (candidate == null)
                continue;

            if (!matchesNameAndDescriptor(m, candidate))
                continue;

            if (hasMoreSpecificClass(m, candidate))
                remove(j);
        }
    }
}
 
Example 7
Project: manifold   File: MapStructExt.java   View Source Code Vote up 6 votes
private static Object invoke( Map thiz, String name, Class returnType, Class[] paramTypes, Object[] args )
{
  Object value = thiz.get( name );
  if( value == null )
  {
    return ICallHandler.UNHANDLED;
  }
  try
  {
    for( Method m : value.getClass().getMethods() )
    {
      if( !m.isDefault() && !Modifier.isStatic( m.getModifiers() ) )
      {
        m.setAccessible( true );
        return m.invoke( value, args );
      }
    }
    return ICallHandler.UNHANDLED;
  }
  catch( Exception e )
  {
    throw new RuntimeException( e );
  }
}
 
Example 8
Project: urdriver   File: URDashboardInvocationHandler.java   View Source Code Vote up 5 votes
@Override
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	if (method.isDefault()) {
		return handleDefaultMessage(proxy, method, args);
	}

	String command = buildURCommand(method);
	// replace the generic placeholder
	command = fillURCommand(command, args);

	String expectedReturn = null;

	// check if @ExpectedReturn is present
	if (method.isAnnotationPresent(ExpectedReturn.class)) {
		ExpectedReturn annotInstance = method.getAnnotation(ExpectedReturn.class);
		expectedReturn = annotInstance.value();
		for (int i = 0; i < annotInstance.parameters().length; i++) {
			expectedReturn += " " + args[i];
		}
	}

	LOG.log(Level.FINE, "call " + proxy.getClass().getInterfaces()[0].getSimpleName() + "." + command);
	//System.out.println(command);
	String string = client.call(command + newline);
	if ((method.getReturnType().equals(Boolean.class) || method.getReturnType().equals(Boolean.TYPE))) {
		if (expectedReturn != null) {
			if (string != null) {
				//System.out.println(string);
				return string.equalsIgnoreCase(expectedReturn);
			} else {
				return false;
			}
		} else {
			return true;
		}
	}
	return string;
}
 
Example 9
Project: ProjectAres   File: Methods.java   View Source Code Vote up 5 votes
public static @Nullable Method trySamMethod(Class<?> iface) {
    if(!iface.isInterface()) return null;

    final Method[] methods = iface.getMethods();
    if(methods.length == 1) {
        return methods[0];
    }

    Method sam = null;
    boolean first = true;
    for(Method method : methods) {
        if(Members.isStatic(method)) continue;

        if(first) {
            // If we've only seen one method, assume it's the SAM
            first = false;
            sam = method;
        } else {
            // If there are multiple methods, and we initially assumed that a default method was the
            // SAM, reverse that assumption.
            if(sam != null && sam.isDefault()) {
                sam = null;
            }

            // If we find an abstract method, and we already have a SAM (which must also be abstract),
            // then the interface is non-functional. Otherwise, assume this method is the SAM and keep
            // going (to make sure there are no more abstract methods).
            if(!method.isDefault()) {
                if(sam != null) {
                    return null;
                }
                sam = method;
            }
        }
    }

    return sam;
}
 
Example 10
Project: OpenJSharp   File: Class.java   View Source Code Vote up 5 votes
void add(Method m) {
    if (length == methods.length) {
        methods = Arrays.copyOf(methods, 2 * methods.length);
    }
    methods[length++] = m;

    if (m != null && m.isDefault())
        defaults++;
}
 
Example 11
Project: OpenJSharp   File: Class.java   View Source Code Vote up 5 votes
void add(Method m) {
    if (length == methods.length) {
        methods = Arrays.copyOf(methods, 2 * methods.length);
    }
    methods[length++] = m;

    if (m != null && m.isDefault())
        defaults++;
}
 
Example 12
Project: jdk8u-jdk   File: Class.java   View Source Code Vote up 5 votes
void add(Method m) {
    if (length == methods.length) {
        methods = Arrays.copyOf(methods, 2 * methods.length);
    }
    methods[length++] = m;

    if (m != null && m.isDefault())
        defaults++;
}
 
Example 13
Project: openjdk-jdk10   File: LoggerFinderAPITest.java   View Source Code Vote up 5 votes
static boolean requiresDefaultBodyFor(Method m) {
    try {
        Method m2 = LoggerBridgeMethodsWithNoBody.class
                .getDeclaredMethod(m.getName(),
                m.getParameterTypes());
        return !m2.isDefault();
    } catch (NoSuchMethodException x) {
        return true;
    }
}
 
Example 14
Project: manifold   File: StructuralTypeProxyGenerator.java   View Source Code Vote up 5 votes
private void genInterfaceMethodDecl( StringBuilder sb, Method mi, Class rootType )
{
  if( (mi.isDefault() && !implementsMethod( rootType, mi )) || Modifier.isStatic( mi.getModifiers() ) )
  {
    return;
  }
  if( mi.getAnnotation( ExtensionMethod.class ) != null )
  {
    return;
  }
  if( isObjectMethod( mi ) )
  {
    return;
  }

  Class returnType = mi.getReturnType();
  sb.append( "  public " )./*append( getTypeVarList( mi ) ).append( ' ' ).*/append( returnType.getCanonicalName() ).append( ' ' ).append( mi.getName() ).append( "(" );
  Class[] params = mi.getParameterTypes();
  for( int i = 0; i < params.length; i++ )
  {
    Class pi = params[i];
    sb.append( ' ' ).append( pi.getCanonicalName() ).append( " p" ).append( i );
    sb.append( i < params.length - 1 ? ',' : ' ' );
  }
  sb.append( ") {\n" )
    .append( returnType == void.class
             ? "    "
             : "    return " )
    .append( maybeCastReturnType( mi, returnType, rootType ) );
  if( !handleField( sb, mi ) )
  {
    handleMethod( sb, mi, params );
  }
  sb.append( "  }\n" );
}
 
Example 15
Project: GitHub   File: Platform.java   View Source Code Vote up 4 votes
@Override boolean isDefaultMethod(Method method) {
  return method.isDefault();
}
 
Example 16
Project: GitHub   File: Platform.java   View Source Code Vote up 4 votes
@Override boolean isDefaultMethod(Method method) {
  return method.isDefault();
}
 
Example 17
Project: urdriver   File: URScriptInvocationHandler.java   View Source Code Vote up 4 votes
/**
 * this method produce the call to UR
 */
/*
 * @Override public synchronized Object invoke(Object proxy, Method method,
 * Object[] args) throws Throwable { // support default messages in
 * interfaces if (method.isDefault()) { return handleDefault(proxy, method,
 * args); }
 * 
 * StringWriter call = new StringWriter(); call.append(method.getName());
 * call.append("("); if (args != null) { Annotation[][] parameterAnnotations
 * = method.getParameterAnnotations(); Annotation[] annotationOfParameter;
 * for (int i = 0; i < args.length; i++) { Validate.notNull(args[i],
 * args[i].getClass().getName()+" must be not NULL"); annotationOfParameter
 * = parameterAnnotations[i]; for (Annotation a : annotationOfParameter) {
 * //resolve the @Name annotation if (a instanceof Named) {
 * call.append(((Named) a).value()); } // resolve the @Min annotation if(a
 * instanceof Min) { try { Validate.isTrue(Long.valueOf(args[i].toString())
 * >= ((Min)a).value(), ((Min)a).message()); } catch (NumberFormatException
 * e){
 * 
 * } } // resolve the @Max annotation if(a instanceof Max) { try {
 * Validate.isTrue(Long.valueOf(args[i].toString()) <= ((Max)a).value(),
 * ((Max)a).message()); } catch (NumberFormatException e){
 * 
 * } } // resolve the @MinFloat annotation if(a instanceof MinFloat) { try {
 * Validate.isTrue(Double.valueOf(args[i].toString()) >=
 * ((MinFloat)a).value(), ((MinFloat)a).message()); } catch
 * (NumberFormatException e){
 * 
 * } } // resolve the @MaxFloat annotation if(a instanceof MaxFloat) { try {
 * Validate.isTrue(Double.valueOf(args[i].toString()) <=
 * ((MaxFloat)a).value(),((MaxFloat)a).message()); } catch
 * (NumberFormatException e){
 * 
 * } } } call.append(args[i].toString()); if (i + 1 < args.length) {
 * call.append(","); } } } call.append(")" + newline); LOG.log(Level.FINE,
 * "call " + proxy.getClass().getInterfaces()[0].getSimpleName() + "." +
 * call.toString()); System.out.println(call.toString()); // if the
 * returntype is null denn wie call the method if
 * (method.getReturnType().equals(Void.class) ||
 * method.getReturnType().equals(Void.TYPE)) {
 * client.write(call.toString()); } else { // TODO return requested value }
 * return null; }
 */

@Override
public synchronized Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
	// support default messages in interfaces
	if (method.isDefault()) {
		return handleDefault(proxy, method, args);
	}
	// this throws an exception if Arguments are wrong
	validateArguments(method, args);

	String command = buildURCommand(method);
	// replace the generic placeholder
	command = fillURCommand(command, args);

	LOG.log(Level.FINE, "call " + proxy.getClass().getInterfaces()[0].getSimpleName() + "." + command);
	return callURCommand(method, command);
}
 
Example 18
Project: manifold   File: DynamicTypeProxyGenerator.java   View Source Code Vote up 4 votes
private void genInterfaceMethodDecl( StringBuilder sb, Method mi, Class ifaceType )
{
  if( mi.isDefault() || Modifier.isStatic( mi.getModifiers() ) )
  {
    return;
  }
  if( mi.getAnnotation( ExtensionMethod.class ) != null )
  {
    return;
  }
  if( StructuralTypeProxyGenerator.isObjectMethod( mi ) )
  {
    return;
  }

  ActualName anno = mi.getAnnotation( ActualName.class );
  String actualName = anno == null ? "null" : "\""+anno.value()+"\"";
  Class returnType = mi.getReturnType();
  sb.append( "  public " )./*append( getTypeVarList( mi ) ).append( ' ' ).*/append( returnType.getCanonicalName() ).append( ' ' ).append( mi.getName() ).append( "(" );
  Class[] params = mi.getParameterTypes();
  for( int i = 0; i < params.length; i++ )
  {
    if( i > 0 )
    {
      sb.append( ", " );
    }
    Class pi = params[i];
    sb.append( pi.getCanonicalName() ).append( " p" ).append( i );
  }
  sb.append( ") {\n" )
    .append( returnType == void.class
             ? "    "
             : "    return " )
    .append( maybeCastReturnType( returnType ) )
    //## todo: maybe we need to explicitly parameterize if the method is generic for some cases?
    .append( "_root" ).append( ".call(" ).append( ifaceType.getCanonicalName() ).append( ".class, \"" ).append( mi.getName() ).append( "\", " ).append( actualName ).append( ", " ).append( mi.getReturnType().getCanonicalName() ).append( ".class, " ).append( "new Class[] {" );
  Class<?>[] parameterTypes = mi.getParameterTypes();
  for( int i = 0; i < parameterTypes.length; i++ )
  {
    if( i > 0 )
    {
      sb.append( ", " );
    }
    Class paramType = parameterTypes[i];
    sb.append( paramType.getCanonicalName() ).append( ".class" );
  }
  sb.append( "}, " );
  sb.append( "new Object[] {" );
  for( int i = 0; i < params.length; i++ )
  {
    if( i > 0 )
    {
      sb.append( ", " );
    }
    sb.append( " p" ).append( i );
  }
  sb.append( "});\n" );
  sb.append( "  }\n" );
}