# How to define macro that only makes argument substitution?

I am having some problems when I define a macro whose content has the lstlisting environment. For example, (assume ! is the escape char inside the lstlisting environment)

\def\mycode#1{
\begin{lstlisting}
class Person {
private int !{\bf #1}!;
int getAge(){
return !#1!;
}
}
\end{lstlisting}
}


When I use \mycode{age} I get an error. Is there any way to fix this (note that I've tried lrbox environment but without success)?

What I really want is some macro definition stuff that simply replaces the arguments in the text and copies the resulting content to where the macro is called. That is, where the following line appeared

\mycode{age}


LaTeX would replace it by

   \begin{lstlisting}
class Person {
private int !{\bf age}!;
int getAge(){
return age;
}
}
\end{lstlisting}


and start processing of \begin{lstlisting} ... \end{lstlisting}.

This should be simple, but unfortunately it seems too complicated (at least for me).

-
I would like to ask you to include the Minimal Working Example, and copy the exact text of the LaTeX Error you get. Then your problem can be much more easily solved. –  yo' Jan 24 '12 at 13:12
You can't; lstlistings is like verbatim, so it cannot go in the argument to another command. –  egreg Jan 24 '12 at 13:21

the environment lstlisting cannot be an argument of another macro.

\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{listings}
\lstnewenvironment{mycode}[1]
{\lstset{escapechar=!}\gdef\myPara{#1}}
{}

\begin{document}

\begin{mycode}{age}
class Person {
private int !\textbf{\myPara}!;
int getAge(){
return !\myPara!;
}
}
\end{mycode}
\end{document}


-
Since I am using frames with beamer, I had to put your code inside a \begin{frame}[fragile]\begin{mycode}{age}...\end{mycode}\end{frame} for it to work: and it worked brilliantly!!! Thanks! –  Mário Jan 24 '12 at 13:43
SORRY!!! MY MISTAKE!!! THAT IS NO SOLUTION, because it requires me to copy the code over and over, and what I want is too write a macro having the code once, and reuse it with different parameters in other places. –  Mário Jan 24 '12 at 13:54
@Mário: In this case you need to store it in an external file an use \lstinputlisting to load it every time you need it. You can write the text into the external file using the filecontents environment. –  Martin Scharrer Jan 24 '12 at 14:20