1/*
2 * Copyright 2003 The Apache Software Foundation
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 */
16package org.mockito.cglib.transform.impl;
17
18import org.mockito.asm.Attribute;
19import org.mockito.asm.ClassVisitor;
20import org.mockito.asm.MethodVisitor;
21import org.mockito.asm.Type;
22import org.mockito.cglib.core.*;
23import org.mockito.cglib.transform.*;
24
25public class AccessFieldTransformer extends ClassEmitterTransformer {
26    private Callback callback;
27
28    public AccessFieldTransformer(Callback callback) {
29        this.callback = callback;
30    }
31
32    public interface Callback {
33        String getPropertyName(Type owner, String fieldName);
34    }
35
36    public void declare_field(int access, final String name, Type type, Object value) {
37        super.declare_field(access, name, type, value);
38
39        String property = TypeUtils.upperFirst(callback.getPropertyName(getClassType(), name));
40        if (property != null) {
41            CodeEmitter e;
42            e = begin_method(Constants.ACC_PUBLIC,
43                             new Signature("get" + property,
44                                           type,
45                                           Constants.TYPES_EMPTY),
46                             null);
47            e.load_this();
48            e.getfield(name);
49            e.return_value();
50            e.end_method();
51
52            e = begin_method(Constants.ACC_PUBLIC,
53                             new Signature("set" + property,
54                                           Type.VOID_TYPE,
55                                           new Type[]{ type }),
56                             null);
57            e.load_this();
58            e.load_arg(0);
59            e.putfield(name);
60            e.return_value();
61            e.end_method();
62        }
63    }
64}
65