1 /*
2  * Copyright 2014 - 2020 Rafael Winterhalter
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package net.bytebuddy.matcher;
17
18 import net.bytebuddy.build.HashCodeAndEqualsPlugin;
19 import net.bytebuddy.description.DeclaredByType;
20 import net.bytebuddy.description.type.TypeDefinition;
21 import net.bytebuddy.description.type.TypeDescription;
22
23 /**
24  * An element matcher that matches the declaring type of another element, only if this element is actually declared
25  * in a type.
26  *
27  * @param <T> The exact type of the element being matched.
28  */

29 @HashCodeAndEqualsPlugin.Enhance
30 public class DeclaringTypeMatcher<T extends DeclaredByType> extends ElementMatcher.Junction.AbstractBase<T> {
31
32     /**
33      * The type matcher to be applied if the target element is declared in a type.
34      */

35     private final ElementMatcher<? super TypeDescription.Generic> matcher;
36
37     /**
38      * Creates a new matcher for the declaring type of an element.
39      *
40      * @param matcher The type matcher to be applied if the target element is declared in a type.
41      */

42     public DeclaringTypeMatcher(ElementMatcher<? super TypeDescription.Generic> matcher) {
43         this.matcher = matcher;
44     }
45
46     /**
47      * {@inheritDoc}
48      */

49     public boolean matches(T target) {
50         TypeDefinition declaringType = target.getDeclaringType();
51         return declaringType != null && matcher.matches(declaringType.asGenericType());
52     }
53
54     @Override
55     public String toString() {
56         return "declaredBy(" + matcher + ")";
57     }
58 }
59