Author: saqibkhan

  • Pattern Class

    Introduction

    The java.util.regex.Pattern class represents a compiled representation of a regular expression.

    Class declaration

    Following is the declaration for java.util.regex.Pattern class −

    public final class Pattern
       extends Object
    
      implements Serializable

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Field

    Following are the fields for java.util.regex.Duration class −

    • static int CANON_EQ − Enables canonical equivalence.
    • static int CASE_INSENSITIVE − Enables case-insensitive matching.
    • static int COMMENTS − Permits whitespace and comments in pattern.
    • static int DOTALL − Enables dotall mode.
    • static int LITERAL − Enables literal parsing of the pattern.
    • static int MULTILINE − Enables multiline mode.
    • static int UNICODE_CASE − Enables Unicode-aware case folding.
    • static int UNICODE_CHARACTER_CLASS − Enables the Unicode version of Predefined character classes and POSIX character classes.
    • static int UNIX_LINES − Enables Unix lines mode.

    Class methods

    Sr.NoMethod & Description
    1static Pattern compile(String regex)Compiles the given regular expression into a pattern.
    2static Pattern compile(String regex, int flags)Compiles the given regular expression into a pattern with the given flags.
    3int flags()Returns this pattern’s match flags.
    4Matcher matcher(CharSequence input)Creates a matcher that will match the given input against this pattern.
    5static boolean matches(String regex, CharSequence input)Compiles the given regular expression and attempts to match the given input against it.
    6String pattern()Returns the regular expression from which this pattern was compiled.
    7static String quote(String s)Returns a literal pattern String for the specified String.
    8String[] split(CharSequence input)Splits the given input sequence around matches of this pattern.
    9String[] split(CharSequence input, int limit)Splits the given input sequence around matches of this pattern.
    10String toString()Returns the string representation of this pattern.

    Methods inherited

    This class inherits methods from the following classes −

    • Java.lang.Object
  • MatchResult Interface

    Introduction

    The java.util.regex.MatchResult interface represents the result of a match operation. This interface contains query methods used to determine the results of a match against a regular expression. The match boundaries, groups and group boundaries can be seen but not modified through a MatchResult.

    Interface declaration

    Following is the declaration for java.util.regex.MatchResult interface −

    public interface MatchResult
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Interface methods

    Sr.NoMethod & Description
    1int end()Returns the offset after the last character matched.
    2int end(int group)Returns the offset after the last character of the subsequence captured by the given group during this match.
    3String group()Returns the input subsequence matched by the previous match.
    4String group(int group)Returns the input subsequence captured by the given group during the previous match operation.
    5int groupCount()Returns the number of capturing groups in this match result’s pattern.
    6int start()Returns the start index of the match.
    7int start(int group)Returns the start index of the subsequence captured by the given group during this match.
  • Capturing Groups

    Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters “d”, “o”, and “g”.

    Capturing groups are numbered by counting their opening parentheses from the left to the right. In the expression ((A)(B(C))), for example, there are four such groups −

    • ((A)(B(C)))
    • (A)
    • (B(C))
    • (C)

    To find out how many groups are present in the expression, call the groupCount method on a matcher object. The groupCount method returns an int showing the number of capturing groups present in the matcher’s pattern.

    There is also a special group, group 0, which always represents the entire expression. This group is not included in the total reported by groupCount.

    Example

    Following example illustrates how to find a digit string from the given alphanumeric string −

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class RegexMatches {
       public static void main( String args[] ) {
    
      // String to be scanned to find the pattern.
      String line = "This order was placed for QT3000! OK?";
      String pattern = "(.*)(\\d+)(.*)";
      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);
      // Now create matcher object.
      Matcher m = r.matcher(line);
      
      if (m.find( )) {
         System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
         System.out.println("Found value: " + m.group(2) );
      } else {
         System.out.println("NO MATCH");
      }
    } }

    This will produce the following result −

    Output

    Found value: This order was placed for QT3000! OK?
    Found value: This order was placed for QT300
    Found value: 0
    
  • Overview

    Java provides the java.util.regex package for pattern matching with regular expressions. Java regular expressions are very similar to the Perl programming language and very easy to learn.

    A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. They can be used to search, edit, or manipulate text and data.

    The java.util.regex package primarily consists of the following three classes −

    • Pattern Class − A Pattern object is a compiled representation of a regular expression. The Pattern class provides no public constructors. To create a pattern, you must first invoke one of its public static compile() methods, which will then return a Pattern object. These methods accept a regular expression as the first argument.
    • Matcher Class − A Matcher object is the engine that interprets the pattern and performs match operations against an input string. Like the Pattern class, Matcher defines no public constructors. You obtain a Matcher object by invoking the matcher() method on a Pattern object.
    • PatternSyntaxException − A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a regular expression pattern.
  • Error

    Introduction

    The java.lang.reflect Error contains the error which can occur during reflection operations.

    Errors Summary

    Sr.No.Error & Description
    1GenericSignatureFormatErrorThrown when a syntactically malformed signature attribute is encountered by a reflective method that needs to interpret the generic signature information for a type, method or constructor.
  • Exceptions

    Introduction

    The java.lang.reflect Exceptions contains the exceptions which can occur during reflection operations.

    Exceptions Summary

    Sr.No.Exception & Description
    1InvocationTargetExceptionInvocationTargetException is a checked exception that wraps an exception thrown by an invoked method or constructor.
    2MalformedParameterizedTypeExceptionThrown when a semantically malformed parameterized type is encountered by a reflective method that needs to instantiate it.
    3UndeclaredThrowableExceptionThrown by a method invocation on a proxy instance if its invocation handler’s invoke method throws a checked exception (a Throwable that is not assignable to RuntimeException or Error) that is not assignable to any of the exception types declared in the throws clause of the method that was invoked on the proxy instance and dispatched to the invocation handler.
  • Introduction

    The java.lang.reflect Interfaces contains the interfaces which are used to obtain reflective information about classes and objects.

    Interface Summary

    Sr.No.Interface & Description
    1AnnotatedElementRepresents an annotated element of the program currently running in this VM.
    2GenericArrayTypeGenericArrayType represents an array type whose component type is either a parameterized type or a type variable.
    3GenericDeclarationA common interface for all entities that declare type variables.
    4InvocationHandlerInvocationHandler is the interface implemented by the invocation handler of a proxy instance.
    5MemberMember is an interface that reflects identifying information about a single member (a field or a method) or a constructor.
    6ParameterizedTypeParameterizedType represents a parameterized type such as Collection<String>.
    7TypeType is the common superinterface for all types in the Java programming language.
    8List<E>This is an ordered collection (also known as a sequence).
    9TypeVariable<D extends GenericDeclaration>TypeVariable is the common superinterface for type variables of kinds.
    10WildcardTypeWildcardType represents a wildcard type expression, such as ?, ? extends Number, or ? super Integer.
  • Proxy 

    Introduction

    The java.lang.reflect.Proxy class provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.

    Class declaration

    Following is the declaration for java.lang.reflect.Proxy class −

    public class Proxy
       extends Object
    
      implements Serializable

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Fields

    Following are the fields for java.lang.reflect.Proxy class −

    • protected InvocationHandler h − the invocation handler for this proxy instance.

    Constructors

    Sr.No.Constructor & Description
    1protected Proxy(InvocationHandler h)Constructs a new Proxy instance from a subclass (typically, a dynamic proxy class) with the specified value for its invocation handler.

    Class methods

    Sr.No.Method & Description
    1static InvocationHandler getInvocationHandler(Object proxy)Returns the invocation handler for the specified proxy instance.
    2static Class<?> getProxyClass(ClassLoader loader, Class<?>… interfaces)Returns the java.lang.Class object for a proxy class given a class loader and an array of interfaces.
    3static boolean isProxyClass(Class<?> cl)Returns true if and only if the specified class was dynamically generated to be a proxy class using the getProxyClass method or the newProxyInstance method.
    4static Object newProxyInstance(ClassLoader loader, Class<?>[] interfaces, InvocationHandler h)Returns an instance of a proxy class for the specified interfaces that dispatches method invocations to the specified invocation handler.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object
  • Modifier 

    Introduction

    The java.lang.reflect.Modifier class provides static methods and constants to decode class and member access modifiers. The sets of modifiers are represented as integers with distinct bit positions representing different modifiers. The values for the constants representing the modifiers are taken from the tables in sections 4.1, 4.4, 4.5, and 4.7 of The Java Virtual Machine Specification.

    Class declaration

    Following is the declaration for java.lang.reflect.Modifier class −

    public class Modifier
       extends Object
    

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Fields

    Following are the fields for java.lang.reflect.Modifier class −

    • static int ABSTRACT − The int value representing the abstract modifier.
    • static int FINAL − The int value representing the final modifier.
    • static int INTERFACE − The int value representing the interface modifier.
    • static int NATIVE − The int value representing the native modifier.
    • static int PRIVATE − The int value representing the private modifier.
    • static int PROTECTED − The int value representing the protected modifier.
    • static int PUBLIC − The int value representing the public modifier.
    • static int STATIC − The int value representing the static modifier.
    • static int STRICT − The int value representing the strictfp modifier.
    • static int SYNCHRONIZED − The int value representing the synchronized modifier.
    • static int TRANSIENT − The int value representing the transient modifier.
    • static int VOLATILE − The int value representing the volatile modifier.

    Constructors

    Sr.No.Constructor & Description
    1Modifier()Default Constructor.

    Class methods

    Sr.No.Method & Description
    1static int classModifiers()Return an int value OR-ing together the source language modifiers that can be applied to a class.
    2static int constructorModifiers()Return an int value OR-ing together the source language modifiers that can be applied to a constructor.
    3static int fieldModifiers()Return an int value OR-ing together the source language modifiers that can be applied to a field.
    4static int interfaceModifiers()Return an int value OR-ing together the source language modifiers that can be applied to an interface.
    5static boolean isAbstract(int mod)Return true if the integer argument includes the abstract modifier, false otherwise.
    6static boolean isFinal(int mod)Return true if the integer argument includes the final modifier, false otherwise.
    7static boolean isInterface(int mod)Return true if the integer argument includes the interface modifier, false otherwise.
    8static boolean isNative(int mod)Return true if the integer argument includes the native modifier, false otherwise.
    9static boolean isPrivate(int mod)Return true if the integer argument includes the private modifier, false otherwise.
    10static boolean isProtected(int mod)Return true if the integer argument includes the protected modifier, false otherwise.
    11static boolean isPublic(int mod)Return true if the integer argument includes the public modifier, false otherwise.
    12static boolean isStatic(int mod)Return true if the integer argument includes the static modifier, false otherwise.
    13static boolean isStrict(int mod)Return true if the integer argument includes the strictfp modifier, false otherwise.
    14static boolean isSynchronized(int mod)Return true if the integer argument includes the synchronized modifier, false otherwise.
    15static boolean isTransient(int mod)Return true if the integer argument includes the transient modifier, false otherwise.
    16static boolean isVolatile(int mod)Return true if the integer argument includes the volatile modifier, false otherwise.
    17static int methodModifiers()Return an int value OR-ing together the source language modifiers that can be applied to a method.
    18static String toString(int mod)Return a string describing the access modifier flags in the specified modifier.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.Object
  • Method 

    Introduction

    The java.lang.reflect.Method class provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method). A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method’s formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.

    Class declaration

    Following is the declaration for java.lang.reflect.Method class −

    public final class Method<T>
       extends AccessibleObject
    
      implements GenericDeclaration, Member

    Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

    Class methods

    Sr.No.Method & Description
    1boolean equals(Object obj)Compares this Method against the specified object.
    2<T extends Annotation> T getAnnotation(Class<T> annotationClass)Returns this element’s annotation for the specified type if such an annotation is present, else null.
    3Annotation[] getDeclaredAnnotations()Returns all annotations that are directly present on this element.
    4Class<T> getDeclaringClass()Returns the Class object representing the class that declares the method represented by this Method object.
    5Object getDefaultValue()Returns the default value for the annotation member represented by this Method instance.
    6Class<?>[] getExceptionTypes()Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying constructor represented by this Constructor object.
    7Type[] getGenericExceptionTypes()Returns an array of Type objects that represent the exceptions declared to be thrown by this Constructor object.
    8Type[] getGenericParameterTypes()Returns an array of Type objects that represent the formal parameter types, in declaration order, of the method represented by this Constructor object.
    9Type getGenericReturnType()Returns a Type object that represents the formal return type of the method represented by this Method object.
    10int getModifiers()Returns the Java language modifiers for the method represented by this Method object, as an integer.
    11String getName()Returns the name of this method, as a string.
    12Annotation[][] getParameterAnnotations()Returns an array of arrays that represent the annotations on the formal parameters, in declaration order, of the method represented by this Method object.
    13Class<?>[] getParameterTypes()Returns an array of Class objects that represent the formal parameter types, in declaration order, of the constructor represented by this Method object.
    14Class<?> getReturnType()Returns a Class object that represents the formal return type of the method represented by this Method object.
    15int hashCode()Returns a hashcode for this Constructor.
    16Object invoke(Object obj, Object… args)Invokes the underlying method represented by this Method object, on the specified object with the specified parameters.
    17boolean isBridge()Returns true if this method is a bridge method; returns false otherwise.
    18boolean isSynthetic()Returns true if this method is a synthetic method; returns false otherwise.
    19boolean isVarArgs()Returns true if this method was declared to take a variable number of arguments; returns false otherwise.
    20String toGenericString()Returns a string describing this Method, including type parameters.
    21String toString()Returns a string describing this Method.

    Methods inherited

    This class inherits methods from the following classes −

    • java.lang.reflect.AccessibleObject
    • java.lang.Object